简体   繁体   中英

Can't able to set the value for useState hook in ReactJS

I used axios to access the 'http://localhost:8000/api/lists/', after accessing it, if I use console.log() , then the values are printing in console, but while setting the state it shows an empty array.. how to set the values of res.data to setArrData(). can anyone help to solve it ?...

const [arrData, setArrData] = React.useState([])
useEffect(()=>
        getData()
},[])

const getData=()=>{
    let inp=field.inp

    axios.post('http://localhost:8000/api/lists/',{
            'input':inp
        },
        {
            headers:{'Content-Type': 'application/json'},
        }
    ).then(res=>{
        if(res.status===200){
            setArrData(res.data)
            console.log(arrData)
            console.log(res.data)
        }
    }).catch(err=>console.log(err))
}

Because setState in asynchronous , so you can't see new state after setState . If you want to see the change of the arrData , you can use useEffect :

useEffect(() => {
  console.log(arrData);
}, [arrData])

Setters in any react hooks are asynchronous. React under the hood sets the state and fires the events to re-render the component or any change that depends on this state, all of it but asynchronously.

setArrData sets the data but to read the updated data, you should use useEffect hook for above-mentioned reason.

useEffect(()=>
    console.log(arrData); <-- on first render the value here will be what you have assigned while defining the state i.e. [] in this case.
}, [arrData]) <--- this is dependency array, 
                   that tell this *useEffect* to run when *arrData* state changes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM