React Redux: Adding to Arrays
Hey all! Another week for me as I complete a coding challenge sent by Shopify. This is my initial state:
state={title: '',resultCt: 0,searchResults: {},nominations: []}
Here, I want to add to nominations which is initiated as an empty array.
I tried state.nominations.push(action.nominations)
which was my first thought that came to mind, but that didn’t work. Instead, I have to do the following:
case 'STORE_NOMINATION':return {...state,nominations: [...state.nominations, action.nominations]}
I have to spread the state first with ...state
and then I have to set nominations to a new array, spreading the original state with ...state.nominations
and then appending action.nominations
to the end.
This worked wonders and it took me a while (as in maybe a day or so… haha) to get to work properly.
That’s all for this week, folks! I look forward to our next talk.
Stay safe everyone!