I would like to display some information which is stored in the AsyncStorage function. It works well, but when I add an item inside this list, I need to restart my application to see the modifications. I think I have to use a useEffect hook but I tried a lot of things and didn't find the solution. If someone could just explain me where is the problem with my code. Thanks you in advance I continue my research by my side.
I set my informations in the AsyncStorage like this:
AsyncStorage.setItem(
`listeElements:${data["fk_produit_id"]}`,
JSON.stringify(data["fk_produit_id"])
);
And there is my code to put the information in a useState array:
const getProduct = async (id) => {
if (id) {
dispatch(authAction.Favorite(id))
.then((response) => {
const newArray = response.array;
setInformations(newArray);
})
.catch((error) => {
console.error(error);
});
} else {
const keys = await AsyncStorage.getAllKeys();
let tempInformations = [...informations];
if (keys) {
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key.startsWith("listeElements")) {
const value = await AsyncStorage.getItem(key);
await fetch(
`http://ip_adress/api/users/favorite?value=${value}`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
},
}
)
.then((response) =>
response.json().then((responseJson) => {
const newArray = responseJson.array;
tempInformations = [...tempInformations, ...newArray];
})
)
.catch((e) => console.log(e));
}
}
setInformations(tempInformations);
}
}
};
useEffect(() => {
getProduct(decoded._id);
const intervalId = setInterval(() => {
setRefreshTime(Date.now());
}, 3000);
return () => clearInterval(intervalId);
}, [decoded]);
I solved this problem by using useIsFocused
of @react-navigation/native
.