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

401
Visualizações
How to call function as initial value of state variable?

I Have a function :

async function setAllValues(value) {
        await stableSort(rows, getComparator(order, orderBy))
            .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
            .forEach((row) => {
                temp = { ...temp, [row.id]: value };
            });
        console.log('| temp', temp);
        return temp;
    }

and a state variable:

const [rowValues, setRowValues] = useState(setAllValues(false));

Now I want the default value of rowValues to be temp(the variable returned from the function), but everytime i log rowValues it logs as a promise. Everytime i call setRowValues, it calls the function setAllValues too(i know this as temp is logged in the function). How do i achieve the desired outcome?

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

0

Use an effect to set the initial value instead once when the page has loaded:

useEffect(() => {
    setAllValues(false)
        .then(setRowValues)
}, [])

Keep the function outside the body of the component so React doesn't complain about it not being in the dependency array.

If you don't need setAllValues to be async, remove async await and set it as initial state with

const [rowValues, setRowValues] = useState() => setAllValues(false))

Currently you're executing it on every render.

about 4 years ago · Juan Pablo Isaza Relatório

0

Now that you don't use async/await anymore, you can just pass a function to useState, as explained in "Lazy initial state":

const [rowValues, setRowValues] = useState(() => setAllValues(false));

The function will only be called the first time the component renders.

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