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

116
Vistas
how to update an object within an array during an asyncThunk.fulfilled action in Redux

I have an AsyncThunk method named likePost when a user clicks like on a post it will send this action via dispatch. The method runs fine, and in my database the Post is updated successfully, but I can't get Redux to update the Post that is liked during the .fulfilled method.

Here is what I'm currently working with:

// shoes = [{_id: '', title: '', likes: []}, ...{}]
export const likePost = createAsyncThunk(
  'posts/likePost',
  async (payload, { rejectWithValue }) => {
    try {
      const response = await userTokenAxios.post(`/${payload}/like`);
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response.data);
    }
  }
);

[likePost.fulfilled]: (state, action) => {
      const post = state.posts.find((post) => post._id === action.payload._id);
      post.likes.push(action.payload.user);
},
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Instead of finding the post, get the index for that object in state.posts const post = state.posts.find((post) => post._id === action.payload._id);

const postIndex=state.posts.findIndex((post)=> post._id === action.payload._id);

Now you can push the user in likes array:

state.posts[postIndex].likes.push(action.payload.user)
about 4 years ago · Santiago Trujillo Denunciar
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