BeHappy
BeHappy

Reputation: 3988

Previous state stored in variable changes too when state change in redux

I am trying to implement like and dislike functionality for posts.

I changed state when user like/dislike post and send request to server and if request failed I changed state to previous state. But previous state change to new state to and I don't know why.

export const dislikePostAction = (
    postId: string,
): ThunkAction<Promise<void>, RootState, {}, AnyAction> => {
    return async (dispatch: ThunkDispatch<{}, {}, AnyAction>, getState): Promise<void> => {
        console.log(getState().GroupPosts.posts); // Even here is new state
        const prevState = getState().GroupPosts.posts;
        console.log(prevState);
        const newState = prevState.map(item => {
            if (item.postId === postId) {
                const newPost = item;
                if (newPost.currentUserLiked === UserPostLike.DISLIKE) {
                    newPost.likeCount = item.likeCount + 1;
                    newPost.currentUserLiked = UserPostLike.NO_ACTION;
                } else {
                    newPost.likeCount = item.likeCount - 1;
                    newPost.currentUserLiked = UserPostLike.DISLIKE;
                }
                return newPost;
            } else {
                return item;
            }
        });
        console.log(prevState);
        dispatch(setPosts(newState));
        const response = await PostsApi.dislikePost(postId);
        if (!response.success) {
            console.log(prevState); // prev state here is same as newState
            dispatch(setPosts(prevState));
        }
    };
};

I am using redux with redux-thunk

Upvotes: 0

Views: 132

Answers (2)

BeHappy
BeHappy

Reputation: 3988

I create new Post object with new Post(item) and problem solved.

const newPost = new Post(item)

Upvotes: 1

adel
adel

Reputation: 3507

because you are assigning newState to prevState and not mutating it so it will refer to address of prevState in the memory and it will change the prevState instead you should create a new Obj or array by mutating prevState like so : if array :

   const prevState =[... getState().GroupPosts.posts];

if Object:

 const prevState ={... getState().GroupPosts.posts};

or you can use Object.assign() which will create a new Object and not refer to the prevState address in memory.

Upvotes: 0

Related Questions