Home > Blockchain >  unable to update object using hooks in react
unable to update object using hooks in react

Time:03-30

I have a function that will update my object value depending on the app name using useState hook. But I am not able to use the hook, it gives error invalid hook call.

Any other way to achieve the same will also work.

var myfun = (function() {

  const APP_NAME= "sample app"
  const [object, setObject] = useState({obj: 'value'})

  if(APP_NAME =="sample app") {
        setObject({obj:'new value'})
         console.log('here')
     }
      return object
});

myfun(); 

CodePudding user response:

Create a custom Hook instead of that Function:

const useMyFun = () => {
    const [object, setObject] = useState({obj: 'value'});

    const APP_NAME = 'sample name';

    useEffect(() => {
        if (APP_NAME === 'sample name') setObject({obj: APP_NAME});
    }, [APP_NAME]);

    return object;
}


// In the component you need it:

const SomeComponent = () => {

    // will update if state changes in the useMyFun Hook;
    const appname = useMyFun();


    // rest of your component code
    ...
}

make sure you use functional components to use this.

NOTE: but this will only be useful if APP_NAME will ever change. otherwhise you could just use a simple ternary operator:

   const object = APP_NAME === 'sample name' ? {obj: APP_NAME} : {obj: 'value'}

CodePudding user response:

Try to move the hook call outside the function like this and the invalid hook call error will disapear i think :

import React from "react";
import { useState } from "react";

function App() {
  const [object, setObject] = useState({ obj: "value" });

  const myfun = () => {
    const APP_NAME = "sample app";
    if (APP_NAME === "sample app") {
      setObject({ obj: "new value" });
      console.log("here");
    }
    return object;
  };

  myfun();

  return (
    ....
  );
}

export default App;

i hope this helps you .

  • Related