I am using Redux to manage the cart state but on restarting the app, the cart state becomes empty. To resolve, I thought of using AsyncStorage to store the data and get it in componentDidMount but it shows null instead of the cart data.
REDUX ACTION CODE
case 'ADD_TO_CART':
{
const updatedCart = [...state.cart];
const item = updatedCart.find(x=>x.key===action.payload.key);
if(item)
{
item.count++;
}
else{
updatedCart.push(action.payload);
}
AsyncStorage.setItem('cart',{...state,cart: updatedCart,total: state.total + 1})
return {
...state,
cart: updatedCart,
total: state.total + 1,
}
}
FETCHING DATA
async componentDidMount() {
const item = await AsyncStorage.getItem('cart'))
console.log(item)
}
I have one more action to delete the cart item in which the same setItem method is used to set the cart state.
When you set an Object to Async storage it should be a string not an object, so use a JSON.strigify and set the item like below
AsyncStorage.setItem('cart',JSON.stringify({...state,cart: updatedCart,total: state.total + 1}));
When you get the item use JSON.parse() to parse them item like below
const item = await AsyncStorage.getItem('cart'))
console.log(JSON.parse(item))
As your requirement is to persist the redux state consider using https://github.com/rt2zz/redux-persist Which will persist the state when you close the app.