React Redux: Adding to Arrays

Lawson Hung
1 min readSep 6, 2020

--

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!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Lawson Hung
Lawson Hung

No responses yet

Write a response