Home > OS >  Troubles with using hook useState()
Troubles with using hook useState()

Time:03-20

Trying to use fetched data into hook useState(fetchedData)

const [car, setCar] = useState({images: []});

useEffect( () => {
        fetchOneCar(id)
            .then(data => setCar(data))
            .finally(() => setLoading(false))
    },[id]);

 const [images,setImages] = useState(car.images)

 console.log(images) // -> [] unpredictably empty
 console.log(car.images) // -> [{},{},{}] (fetched data)

How to properly set data into useState() in my case ?

CodePudding user response:

ok look first car is {images:[]} then images is [] and then car turns into whatever data you fetched in use effect just because you declare useState after use effect doesn't mean it will run after useEffect. First all the useStates run and then the effects. that's the law. so there is no unexpected result. To fix this in yur use effect do this:

useEffect( () => {
        fetchOneCar(id)
            .then(data => {
             setCar(data);
             setImages(data)
             })
            .finally(() => setLoading(false))
},[id]);

CodePudding user response:

According to your code, I expect that you want to fill the images with the result from data. If it is, then you have to put the setImages(data.images) inside the resolved promise, after the setCar(data). It should be like this one

const [car, setCar] = useState({images: []});
const [images,setImages] = useState();
useEffect( () => {
    fetchOneCar(id)
        .then(data => {
              setCar(data);
              setImages(data.images);
         })
        .finally(() => setLoading(false))
},[id]);

I put the useState() for images at the top for better reading.

  • Related