currentUserPosts will have a post object with an id that either matches a tempId, an Id, or nothing.
If there's a tempId match there won't be an id match and vice versa.
This code works but there's something about it I don't like. How can it be refactored?
let postIndex;
postIndex = currentUserPosts.findIndex(post => post.id === upsertParams.tempId);
if (postIndex === -1) {
postIndex = currentUserPosts.findIndex(post => post.id === upsertParams.id);
}
if (postIndex === -1) {
currentUserPosts.push(upsertParams);
} else {
currentUserPosts[postIndex] = upsertParams;
}
Complete function:
const upsertIntoApolloCache = (upsertParams) => {
try {
const data = client.readQuery({
query: USER_POSTS_QUERY,
});
const currentUserPosts = data.currentUser.posts;
const postIndex = currentUserPosts.findIndex(
post => post.id === upsertParams.tempId || post.id === upsertParams.id
);
if (postIndex === -1) {
currentUserPosts.push(upsertParams);
} else {
currentUserPosts[postIndex] = upsertParams;
}
client.writeQuery({
query: USER_POSTS_QUERY,
data,
});
} catch (error) {
console.log('!!ERROR in upsertIntoApolloCache!!', error);
}
};