pingeyeg
pingeyeg

Reputation: 680

How to append to Redux state

I'm trying to append to my redux state, but having an issue understanding where I'm wrong. At the moment, I'm getting an error state is not iterable.

enter image description here

reducer

const CURRENT_USER = "CURRENT_USER";

const reducer = (state = [], action) => {
  switch(action.type) {
    case CURRENT_USER:
      const currentUser = [
        ...state,
        action.payload
      ];
      return currentUser;
    default:
      return state;
  }
}

export default reducer;

dispatch

posts.forEach((post: BlogPost) => {
  if (post.userId === currentUserPosts) {
    dispatch({
      type: "CURRENT_USER",
      payload: { ...post },
    });
  }
});

Upvotes: 0

Views: 916

Answers (1)

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

So from the reducer after updating the state you have to return the new state

so as I see

case CURRENT_USER:
    return {
      currentUser: [...state, action.payload]
    }
.....

You are returning an object {currentUser: [..} this will be the new state after the action happens

so again if you call this, state is an object ({currentUser: [..}) if you try to treat that as iterable (array) you will get this error

[...{currentUser: []}]

Upvotes: 2

Related Questions