Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

159
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda