Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda