Home > Net >  How to call function as initial value of state variable?
How to call function as initial value of state variable?

Time:06-04

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?

CodePudding user response:

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.

CodePudding user response:

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.

  • Related