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

154
Visualizações
Cannot change variable in useEffect in React

I am trying to change the values of variables within a useEffect call in js React. I notice that the values get changed inside of the function, but the global value is not changed.

var O_name = "";
var A_name = "";
var A_platform = "";
var C_name = "";

function Statsview( {backButton} ) {
    const urlParams = new URLSearchParams(window.location.search);
    const name = urlParams.get('name');
    
    var data = useRef();
    const [overwatchName, setO_Name] = useState([]); 

    
    useEffect(() => {
        console.log('mounted')
        database.collection('USERS').where('name','==',name).get().then(snapshot => {
            snapshot.forEach(doc => {
                var data = doc.data()
                O_name = data.overwatch;
                console.log(O_name)
                A_name = data.apexLegends;
                console.log(A_name)
                A_platform = data.apexLegendsPlatform;
                console.log(A_platform)
                C_name = data.chess;
                console.log(C_name)
            })
        }).catch(error => console.log(error))      
    },[]);

    console.log("oname: ",O_name)
    console.log("aname: ",A_name)
    console.log("aplat: ",A_platform)
    console.log("cname: ",C_name)
...
...
}

The console logs inside of the useEffect show updated values for each varaible. However, the console logs outside of the useEffect show that the values for each variable are blank.

How do I change these global values?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Global variables and functions are initiated when React first load all the scripts, that means when you first load (or reload) the page. React itself is not aware of the mutation of these global variables.

Your code flow is like this.

  1. Global variables are initialized.
  2. console.log() prints the content when a component is loaded.
  3. An async call mutates the global variables => React is not aware of them. hence does not re-render your component. Hence, console.log() is not called.

You should use state hook to store these variables so React knows they are changed.

about 4 years ago · Juan Pablo Isaza Relatório

0

You should use useRef for this case.

so for simple example.

function MyComponent(){
   const A_name = useRef('');
   
   useEffect(() => {
      A_name.current = 'new value'
   }, []);
}

You can change/access the variable with .current property

You can read more at docs here: https://reactjs.org/docs/hooks-reference.html#useref

It mentioned: useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

So it would fit your objective

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