Update a flatlist with useEffect and asyncstorage data

837 Views Asked by At

I have two screens, the first screen (Entry.js) is like a form where I input some data and I save it in the asyncstorage

const entryVehicleLocal = async ({values}) => {

    const currentDay = new Date();
    const date = String(currentDay);
    const dateSlice = date.slice(4, -15);
    const issuedDate = String(dateSlice);
    values.issuedDate = issuedDate;
            
    const id = shortid.generate();

    const valuesLocal = {
        id: id,
        issuedDate: issuedDate,
        type: values.type,
        color: values.color,
    }

    saveCar(JSON.stringify(valuesLocal));
    
}

const saveCar = async (carJSON) => {
    try {
        await AsyncStorage.setItem('car', carJSON);
        console.log('Logrado');
    } catch (error) {
        console.log(error);
    }
}

Then I have a second screen (Parking.js) where i want to show in a flatlist the data I save in my asyncstorage but here is my problem, I was trying to use useEffect to automatically refresh my data but when I do that it's just refreshing one time and then never update the data so the flatlist just show one element and I want all the items I'm input in my first screen

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

useEffect(() => {
    getStorage();
}, [setCarList]);

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

I hope you can help me

1

There are 1 best solutions below

0
On

set extradata in your flatlist component to re-render upon data update,

<FlatList ... extraData={carList}/>