Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

158
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda