Having problem in understanding REDUX code

81 Views Asked by At

I am trying to create shopping basket through Redux Toolkit. I am finding it hard to understand this piece of code that what is purpose of all this code. Specifically those if conditions. Cant understand how add and remove reducer is working

const basketSlice = createSlice({
  name: "basket",
  initialState: INITIAL_STATE,
  reducers: {
    add: (state, action) => {
      return state.map(item => {
        if (item.id !== action.payload.id) {
          return item
        }

        return {
          ...item,
          added: true
        }
      })
    },
    remove: (state, action) => {
      return state.map(item => {
        if (item.id !== action.payload.id) {
          return item
        }

        return {
          ...item,
          added: false
        }
      })
    }
  }
})
1

There are 1 best solutions below

2
On

You should check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Basically it loops over the state items, creating a new array from what is returned in each iteration of the loop.

So, what it does for, say, the remove reducer:

  • Loop over each item in state, each time returning something that will be an entry in the new array
  • The if section checks if the id of the current loop element is the same than the one we want to remove: if it's not the same ID, we return the item "as is", if it's the same ID, we return added: false so we know it was removed.
  • In the end, you get a new array that was processed through this map function, allowing to do whatever check you need to.

Say I have an array with 3 items:

const state = [
 { id: 12, name: "Fancy Phone", added: true, },
 { id: 54, name: "Leather Jacket", added: true, },
 { id: 564, name: "AI World-Dominating Robot", added: true, },
]

And I want to remove the "AI World-Dominating Robot" because I don't want anymore trouble:

// Create a new array from the .map
return state.map(item => {
  // here we loop over each item one by one
  // IF the ID in the action payload (thus the ID you want to remove) is not the same as the current item ID, we don't want to remove it
  if (action.payload.id !== item.id) {
    return item // so we return the item "as-is", and as we returned something, the .map loop moves to the next item
  }
  return { ...item, added: false } // otherwise, we set "added: false" to flag the fact it's removed