I am new to react native and I don't know how best to do this. I have an array of objects saved in AsyncStorage that look like this;
[
{
userId: 1,
id: 1,
title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
body: "quia et suscipit
suscipit recusandae consequuntur expedita et cum
reprehenderit molestiae ut ut quas totam
nostrum rerum est autem sunt rem eveniet architecto"
},
{
userId: 1,
id: 2,
title: "qui est esse",
body: "est rerum tempore vitae
sequi sint nihil reprehenderit dolor beatae ea dolores neque
fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis
qui aperiam non debitis possimus qui neque nisi nulla"
}
]
I can perform full crud operation in AsyncStorage without internet connection. However, I want to send this data to a remote mongoDB database. If a post exist, I want the post to be updated, if it doesn't exist, I want the post to be created.
I am using redux. So what I did was to loop through the array from AsyncStorage, if an object has "_id", it means the object already exist in the database, if it doesn't then create the object like so;
useEffect(() => {
posts.map((post) => {
if(!("_id" in post)) {
dispatch(sendNewPostToDatabase(post))
} else{
dispatch(updatePostInDatabase(post._id, post))
}
})
},[posts])
the sendNewPostToDatabase action look like this;
export const sendNewPostToDatabase = (post) => async (dispatch) => {
try {
const { data } = await api.createPost(post);
let savedItems = [];
const response = await AsyncStorage.getItem("queue");
if (response) savedItems = JSON.parse(response);
const updatedList = await savedItems.map((item) => item.id === data.id ? data : item)
dispatch({ type: FETCH_POSTS_BY_USER, payload: updatedList });
return AsyncStorage.setItem("queue", JSON.stringify(updatedList));
} catch (error) {
console.log(error.response)
}
}
And then my updatePostInDatabase action look like this;
export const updatePostInDatabase = (id, post) => async (dispatch) => {
try {
await api.updatePost(id, post);
} catch (error) {
console.log(error);
}
}
The problem is that, this approach result in an infinite loop, where the app keeps sending the data over and over again repetitively creating new post even if the post already exist in the database. Also, I want to send only new posts and update only posts with new changes. Please how can I be able to effectively achieve this?