node.jsreactjsnpmnpm-installformsy-react

monkey patching a function used in formsy-react library


I use formsy-react v1.1.5 for validation and i have about 100 input field and its unbelievably slow because of an unnecessary object.assign function in their code. I know that the higher versions fixed this issue but i can not update it right now.

I have totally no idea about monkey patching and i dont want to use any patching libraries to get the work done. I would like to understand how it can be patched.

this code:

getCurrentValues = () => (
 this.inputs.reduce((data, component) => {
   const { name } = component.props;
   const dataCopy = Object.assign({}, data); // avoid param reassignment
  dataCopy[name] = component.state.value;
  return dataCopy;
 }, {})
)

 getPristineValues = () => (
  this.inputs.reduce((data, component) => {
    const { name } = component.props;
    const dataCopy = Object.assign({}, data); // avoid param reassignment
   dataCopy[name] = component.props.value;
  return dataCopy;
 }, {})
)

I want to make the following changes:

getCurrentValues = () => (
this.inputs.reduce((data, component) => {
  const { name } = component.props;
  data[name] = component.state.value;
  return data;
}, {})
)

  getPristineValues = () => (
this.inputs.reduce((data, component) => {
  const { name } = component.props;
  data[name] = component.props.value;
  return data;
}, {})
)

Thanks.


Solution

  • The easiest and fastest way:

    Go to "node_modules/formsy-react/lib", open the file you want to patch, change it and save.

    Next time you execute it, it will use the file changed.

    The only problem with this is that you need to do it again each time you do an npm install in every computer.

    A better approach is create a file .js with the file patched, create a script in package.json that copies it in the right place and add a reminder in the README that you need to execute the script after executing npm install.

    It could be something like this:

      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "node index.js",
        "patch": "mv patchedFile.js ./node_modules/formsy-react/lib/{fileName}.js"
      },
    

    Being patchedFile.js in the project root and having the same content than {fileName}.js with the modification.

    And just execute "npm run patch" after "npm install".