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

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

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 Denunciar

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 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