code.cycling
code.cycling

Reputation: 1274

A better way to handle updating state in reducer

So I'm trying to learn react-redux and in my reducer GET_COMMENTS. I need to check first if there is already items in state.comments so I try to use if-else statement and it works. But maybe there's still a better way to handle it ?

case 'GET_COMMENTS':
        let list = []
        if (state.comments.length > 0) { // check if there's an item 
            list = state.comments // pass existing state
            action.payload.data.map(comment => { // map through new data
                list = [...list, comment] // dont know if this is the right way but it works
            })
        } else {
            list = action.payload.data // if state.comments is empty directly pass new data
        }
        return {
            ...state,
            comments: list,
            next: action.payload.next
        }

UPDATE: I decided to go with Gabriele answer as I think its the best approach. And Today I learn that .concat() method is used to join two or more arrays. This method does not change the existing arrays, but returns a new array, containing the values of the joined arrays.

Upvotes: 0

Views: 42

Answers (2)

Roman Mahotskyi
Roman Mahotskyi

Reputation: 6685

Yes it is correct. I would simplify your approach to

...
case 'GET_COMMENTS':
  return {
    ...state,
    comments: [...state.comments, ...action.payload.data]
    next: action.payload.next
  };

Note: I consider that action.payload.comments is a new array of comments. And initial state is { comments: [] }.

Upvotes: 2

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196236

I would just do

case 'GET_COMMENTS':
  return ({
    ...state,
    comments: state.comments.concat(action.payload.data),
    next: action.payload.next
  });

Upvotes: 2

Related Questions