Home > Back-end >  NextJS useState Array not properly setting the state
NextJS useState Array not properly setting the state

Time:08-03

I'm trying to save an array to a useState array but the state is not updating properly. When the code below is run, the variable first will return the values properly but the variable "data" returns an empty array.

When I add console.log("restart") under line 5, it is shown that it is console.log twice when the page is first loaded and another time after the useEffect is called.

import { jsonFile } from "../public/data.json";
import {useState, useEffect} from 'react'

...

    const [data, setdata] = useState<any>([]) //line 5

    let first:any = [];

    function getFirst(){
        for (var i = 0; i < jsonFile.length; i  ){
            if(jsonFile[i].number == 1){
                first.push(jsonFile[i])
            }
        }
    }

    useEffect(() => {
        getFirst()
        setdata(old => [...old, first])
        console.log(first)
        console.log(data)
    },[])
...

CodePudding user response:

Since first is an array you should change your setdata call to:

setdata((old) => [...old, ...first]);

Also, you should change the type of the data state to any[]:

const [data, setdata] = useState<any[]>([])

CodePudding user response:

You need to destructure first so that all the elements from first are spread in data array.

You can do something like this:

setData([...data, ...first]);

What I've done here is call the setData function and passed an array where the old contents of data array are first populated and then the contents of first array are populated.

Also, try to use camel case when naming useState functions, instead of setdata you should use the naming setData, it's more consistent with the notations :)

  • Related