I have a React Context Provider that has an stateful array of "posts".
My idea is to provide 3 methods, one for adding, another for updating and a last one for deleting.
So, if the user fetches 10 posts from the database, they have to be saved in the context provider:
const newPosts = await fetchPosts(cursor, startAfter, limit);
// Save the new posts in the Posts Context
contents.addContents(newPosts);
but, what about if one of these posts are already saved? I need to ignore already added posts.
This is my Contents Context:
export function ContentsProvider({ children }) {
const [contents, dispatch] = useReducer(contentsReducer, new Map([]));
const addContents = (newContents) => {
dispatch({
type: "add-contents",
newContents,
});
}
...
return (
<ContentsContext.Provider
value={{
addContents,
...
}}
>
{children}
</ContentsContext.Provider>
)
}
How can I avoid adding already saved contents? I mean, is the correct way to do it inside the method addContents method or inside my reducer?
const contentsReducer = (contents, action) => {
switch (action.type) {
case "add-contents": {
const { newContents } = action;
return new Map([...contents, ...newContents]);
}
...
};
I am asking because conditionally updating state inside a reducer seems strange to me, maybe it is an anti-pattern.
Any ideas?
export default (contents, action) => {
switch (action.type) {
case "add-contents": {
let { newContents } = action;
// Avoid storing already added contents
newContents = newContents.filter(
(newContent) => !contents.get(newContent.id)
);
if (!newContents.length) return contents;
return new Map([...contents, ...newContents]);
}
...