Search code examples
reactjsreduxreact-reduxredux-toolkit

State are not updating inside reducer? redux/toolkit


i am using redux toolkit for my project i have a problem i access the state inside a reducer using current function provided by reduxjs but when i update the state it is not updating i don't know why i did a lot of research on that but i didn't find anything useful here is my reducer

import { createSlice,current } from "@reduxjs/toolkit";

const initialState = {
  posts: [],
};

const postSlice = createSlice({
  name: "posts",
  initialState,
  reducers: {
    updatePosts: (state, action) => {
      const postsArray = Object.values(action.payload);
      // state.posts = state.posts.concat(Object.values(action.payload));
      state.posts.push(...postsArray);
    },
    updateLikes: (state, action) => {
      const { postId, userId } = action.payload;
      const currentState = current(state.posts)

    },
  },
});

export const { updatePosts, updateLikes } = postSlice.actions;
export default postSlice.reducer;

inside updateLikes i am getting postId, and userId which i am getting successfully when i use dispatch. but when i get the current state using current function it also return me the state but when i try to push or remove anything from array nothing happen doesn't show any error or anything else


Solution

  • current function from RTK is used to get a snapshot of the state for read-only purposes. So for modifying the state in updateLikes reducer you should directly modify the state, smth like:

    updateLikes: (state, action) => {
      const { postId, userId } = action.payload;
      const post = state.posts.find(post => post.id === postId);
      // Any logic connected to post update, like post.likes = ...
    },