Note: I am not using Redux (instead, React Context + reducers)
I have the following reducer:
export default (contents, action) => {
switch (action.type) {
case "like-content": {
let { content } = action;
const prevContent = contents.get(content.id);
return new Map([...contents, [content, {
...content,
totalLikes: prevContent.totalLikes + 1
}]);
}
...
And I need to check if the given content is stored in my contents map before updating the state.
I have think about updating my code to:
export default (contents, action) => {
switch (action.type) {
case "like-content": {
let { content } = action;
const prevContent = contents.get(content.id);
if (!prevContent) throw Error("The content doesn't exist");
return new Map([...contents, [content, {
...content,
totalLikes: prevContent.totalLikes + 1
}]);
}
...
But, personally, it seems incorrect, as I am "breaking" the state update.
How can I handle this?