useState: updating array with asyncstorage data

146 Views Asked by At

I need to update an array passing some data that I have in my asyncstorage, the problem is the data i send in set don't recive the argument i'm passing and in consequence my state isn't print the data i' m trying to pass

    const [carList, setCarList] = useState([]);
        
    const getStorage = async () => {
        const newCar = await AsyncStorage.getItem('car');
        const car = JSON.parse(newCar)
        setCarList([...carList, car]);
        console.log(carList);
    }

The console.log supose to be like:

Array [ Object { "id": 1, "marca": "Alfa Romeo", "modelo": "MiTo", "observaciones": "Color rojo", "placas": "A00-AAA" } ]

but the result i have is

Array []

1

There are 1 best solutions below

0
On

I recommendo you to use useEffect:

import React, {useState, useEffect} from react;

const [carList, setCarList] = useState([]);

// When the component did mount you will fetch for data and update your state
 useEffect(async ()=>{
    
    const newCar = await AsyncStorage.getItem('car');
    const car = JSON.parse(newCar);
    setCarList([...carList, car]);
    console.log(carList);

 },[]);