⊗jsrxPmRDEP 23 of 57 menu

Changing product data in Redux store

We've learned how to add products, but what if we want to change the product information? Let's look at how to do that in this and subsequent lessons.

Let's open our product application and go to the productsSlice.js file. Let's start with the fact that we need to write another reducer for the products slice, which will be launched when the product is updated. Let's call it productUpdated and add it to the reducers field after the productAdded reducer. We will also immediately pass it the state and action parameters, based on which, as we remember, the reducer works:

reducers: { productAdded(state, action) { state.push(action.payload) }, productUpdated(state, action) {}, },

Now let's think about what data we will need to update the product. First of all, this is id, by which we will be able to find the product we are interested in in the store. The rest of the data - name, description, price and quantity will be for us to change. We will get all these values ​​from the payload property of the action object that will come to us, and if we wrote it manually, it would look like the one shown below. Note that the expected value of the payload property is one argument, so we will pass an object here (we will talk about this later):

{ type: 'products/productUpdated', payload: {id, name, desc, price, amount} }

With the basics out of the way, we can now write the code for productUpdated in curly braces. First, we get the changed data from the action object:

productUpdated(state, action) { const { id, name, desc, price, amount } = action.payload },

Now we will find the product that needs to be changed based on the obtained id:

productUpdated(state, action) { const { id, name, desc, price, amount } = action.payload const desiredProduct = state.find(product => product.id === id) },

If such a product is found in the store, we will replace its data with new values:

productUpdated(state, action) { const { id, name, desc, price, amount } = action.payload const desiredProduct = state.find(product => product.id === id) if (desiredProduct) { desiredProduct.name = name desiredProduct.desc = desc desiredProduct.price = price desiredProduct.amount = amount } },

All that's left for us to do is export the action creator for use in the component, which will kindly create createSlice for us. Let's add it to the export at the end of the file, along with the existing productAdded:

export const { productAdded, productUpdated } = productsSlice.actions

Open your app with students. After reviewing the lesson, in the studentsSlice.js file, add another reducer for productsSlice, which will update the student data in the store if the user changes it. Name it studentUpdated.

How would your action object look in this case? Send its code in the answer.

At the end of the file, export the resulting action creator studentUpdated.

enru