Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

214
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda