Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
unable to update object using hooks in react

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(); 
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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'}
about 4 years ago · Juan Pablo Isaza Report

0

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 .

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!