Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

389
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!