How can I convert Redux toolkit reducers In react

I've started to learn Redux with React, I got stuck in a part of my project which is an E-commerce store that when the user clicks on add to cart I want to update the quantity and add the article to the bag. I've implemented Redux for other functionalities but I found a solution for my problem with ReduxToolkit which I didn't learn yet

How can I convert this code written with a redux toolkit to Redux?

import { createSlice } from "@reduxjs/toolkit";

const cartSlice = createSlice({
  name: "cart",
  initialState: {
    products: [],
    quantity: 0,
    total: 0,
  },
  reducers: {
    addProduct: (state, action) => {
      state.quantity += 1;
      state.products.push(action.payload);
      state.total += action.payload.price * action.payload.quantity;
    },
  },
});

export const { addProduct } = cartSlice.actions;
export default cartSlice.reducer; 

1 answer

  • answered 2021-10-12 18:36 Erfan

    I believe your current store is created in such a way:

    const rootReducer=combineReducers({
              firstFunctionality:firstFunctionalityReducer,
              secondFunctionality:secondFunctionalityReducer,
              ... })
    

    Now you want to create a new functionality like cart,

    first you create the initial state:

    const initialState={
        products: [],
        quantity: 0,
        total: 0,
      }
    

    Now the reducer :

    const cartReducer=(state=initialState,action)=>{
    
             switch (action.type) {
                 case "addProduct":return {...state,
                                          quantity:state.quantity+1,
                                          products:[...state.products,action.payload],                                 
                                          total:action.payload.price*action.payload.quantity;
                 
                 case "default":return state}
                 }
    

    Now we use this new reducer:

    const rootReducer=combineReducers({
              firstFunctionality:firstFunctionalityReducer,
              secondFunctionality:secondFunctionalityReducer,
              cartFunctionality:cartReducer
              ... })
                                 
    

    Now whenever you need want to add a product you dispatch this action:

    const addProductAction=(product)=>({type:"addProduct",payload:product})
    

    one last thing is how you dispatch actions and use the state. which can be achieved by either useSelector and useDispatch hooks, or mapDispatchToProps and mapStateToProps and connect HOC.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum