0

I am learning to write reducers for arrays. For example, one of the reducers changes array elements from integers to arrays.

Original state:

[0, 3, 5, 3, 9, 8]

Action:

case ADD_NEST:
      return state.map(i => [i, action.payload]);

New state:

[[0, 0], [3, 0], [5, 0], [3, 0], [9, 0], [8, 0]]

I'm trying to write a reducer that would change the second element of sub-arrays based on the condition of the first one. (eg, if the first element of the subarray is greater than 3, change the second element to 1).

[[0, 0], [3, 0], [5, 1], [3, 0], [9, 1], [8, 1]]

so far I have (not much as I'm stuck):

case SET_BIT:
      return state.map(i => (i[0] > 3 ? ??? : i));

Thank you for advice!

1 Answer 1

1

Like this?

case SET_BIT:
  return state.map(i => (i[0] > 3 ? [i[0], i[1] + 1] : i));

Although, that's a bit weird/dangerous. What happens if SET_BIT gets dispatched when your state of that reducer is still a flat array? Then the above code will crash. Then you would have to do something like:

case SET_BIT:
  return state.map(i => (
    Array.isArray(i) && i[0] > 3
      ? [i[0], i[1] + 1]
      : i
  ));

I don't know the details of what you are trying to do here, but generally speaking I think it's best to keep the structure of the state of a reducer consistent. I tend to avoid nested structures in the state of my redux store because I try to keep the state of my redux store as normalized as I can. That makes reducers a lot easier to maintain. If I need to nest stuff for my views I usually do that in the selectors.

But again, I lack context, so not sure if any of this advice is relevant to you. :-)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - I'll try it when I get back from work. Basically, I'm testing out simple scenarios to learn as what I really try to do is I have an array of numbers (which are displayed on a grid) but then I need to indicate if each grid element/number is displayed (on/off) - that's why I thought that would be the best way of representing it The initial state would be as follows where all the numbers are hidden: [[number, 0], [number, 0], [number, 0],.....] so when I want to display any of the elements I'll just change the 0 to 1. Is that the best way of organising it?

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.