⊗jsrxPmWFRAA 17 of 57 menu

Reducer and action in Redux

In the previous lesson we finished the form for adding a product and displayed it on the main page. But the added data is not saved yet, in other words, the new product is not added to the existing ones in the store. Let's fix this.

To begin with, in our product application, we will open the productsSlice.jsx file and write the reducer function for createSlice in the reducer property, which will add the product to the store based on the current state and action passed to it. It should be noted that here we are not passed the entire state, but only the part of it that is responsible for the products (the products slice only knows about it). The object with the new product will be in the payload property of the action object, which will be generated by the handler when the save button is pressed in the form. As a result, the reducer productAdded will look like this in the code createSlice:

const productsSlice = createSlice({ name: 'products', initialState, reducers: { productAdded(state, action) { state.push(action.payload) }, }, })

What about action? At the very beginning of the tutorial, we mentioned that action is some event, represented as an object, describing what happened in the application. We also talked about the fact that you can use the action creator function, which will create such an object for us, for example like this:

const addProduct = newProduct => { return { type: 'products/productAdded', payload: newProduct } }

The good news is that we don't have to do anything, the createSlice function we use will do it for us. Once we write the reducer, it will automatically create an action creator with the same name for us. All we have to do is export the resulting action creator for further use in components. Let's do it at the end of the file before exporting the reducer, like this:

export const { productAdded } = productsSlice.actions export default productsSlice.reducer

Open your application with students, and then the file studentsSlice.jsx, add the value of the field reducer for createSlice, as shown in the lesson.

Add an export of the resulting action creator function to the end of the studentsSlice.jsx file.

enru