Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
React - Conditionally update state inside reducer

Introduction

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.

Problem

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?

This is my current solution:

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]);
    }
    ...
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!