1
const initialState: FriendsState = {
  friends: []
};

export default function friends(state = initialState, action: Action): FriendsState {
  switch (action.type) {
    case TYPES.ADD_TO_FRIENDS:
      return assign({}, state, {
        friends: state.friends.push(action.payload.friendId)
      })
  }
}

I am basically trying to add a friendId that looks like something like 1003 or something into my friends array. Is that the right way of going about it?

What about if I have to add an object? something like { friendId: 1003, category: 4 }

export interface Friends {
  friends: FriendIds[];
};

interface FriendIds {
  id: number;
}
5
  • i get an error that says TypeError: state.friends.push is not a function Commented Aug 18, 2016 at 18:42
  • 1
    Then I suppose it's not an array as you assumed. Remember also that push does not return the resulting array, so in some cases you may want to use concat. Commented Aug 18, 2016 at 18:43
  • I think I am defining my array wrong then. Can you please take a look at my edit? Commented Aug 18, 2016 at 19:00
  • The first push will rewrite friends to an integer (which is what push returns). Then the second push will fail, because you can't push to an integer. Commented Aug 18, 2016 at 19:02
  • thanks i now understand concat vs push better !! Commented Aug 18, 2016 at 19:08

1 Answer 1

2

I am basically trying to add a friendId that looks like something like 1003 or something into my friends array. Is that the right way of going about it

Yes push will add to the array.

However it mutates the array. Seeing as you are using Redux (docs : http://redux.js.org/) you want to use non mutating methods. e.g concat:

const initialState: FriendsState = {
  friends: []
};

export default function friends(state = initialState, action: Action): FriendsState {
  switch (action.type) {
    case TYPES.ADD_TO_FRIENDS:
      return assign({}, state, {
        friends: state.friends.concat([action.payload.friendId])
      })
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.