How can I create a cart with reduxjs/toolkit?

Viewed 39

I am creating a cart for a mobile shop. I want to change it to work with @reduxjs/toolkit. I have the reducer code below that I need to change to run with reduxjs/toolkit

    import {
    ADD_TO_CART,
    REMOVE_FROM_CART,
    CLEAR_CART
} from '../constants';

const cartItems = (state = [], action) => {
    switch (action.type) {
        case ADD_TO_CART:
            return [...state, action.payload]
        case REMOVE_FROM_CART:
            return state.filter(cartItem => cartItem !== action.payload)
        case CLEAR_CART:
            return state = []
    }
    return state;
}

export default cartItems;

The output for the above is below array - which is what is getting pushed to Cart. I want to change the above code to work with reduxjs and output similar output as below and increment / decrement the cart quantity.

Array [
  Object {
    "product": "5f15d92ee520d44421ed8e9b",
    "quantity": 1,
  },
  Object {
    "product": "62e5285f92b4fde9dc8a384c",
    "quantity": 1,
  },
  Object {
    "product": "62e52c4892b4fde9dc8a3881",  
    "quantity": 1,
  },
  Object {
    "product": "62e52c4892b4fde9dc8a3881",
    "quantity": 1,
  },

]

I have created the new store below

import {
  configureStore
} from "@reduxjs/toolkit";
import cartItems from "./Reducers/cartslice";
import {
  combineReducers
} from "redux";
const reducer = combineReducers({
  cartItems: cartItems,
});
const store = configureStore({
  reducer,
});
export default store;

I am stuck at creating a new reducer with reduxjs, below is the code.

import { createSlice } from '@reduxjs/toolkit';
const cartItems = createSlice({
  name: 'cart',
  initialState: {cart:[]},
  reducers: {
    addToCart: (state, action) => {
      //What do I input here
    },
  },
});
export default cartItems.reducer;

1 Answers

You can follow this logic. Make it work first with your proiject and then scale it further.

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { cartService } from "./cart.service"


const initialState = {
  cart: [],
  isLoading: false,
  isSuccess: false,
  isError: false,
}

export const addToCart = createAsyncThunk(
  'cart/add',
  async(cartData, thunkAPI) => {
try {
  return await cartService.addToCart(cartData) /* this is your axios (or any other) call, you can keep it in separate file or have it here, up to you I choose the separation of concerns */
} catch (error) {
  console.log(error);
  return thunkAPI.rejectWithValue(error)
}
  }
)

export const cartSlice = createSlice(
  {
    name: 'cart',
    initialState,
    reducers: {
      reset: (state) => initialState
    },
    extraReducers: (builder) => {
      builder
        .addCase(addToCart.pending, (state) => {
          state.isLoading = true
        })
        .addCase(addToCart.fulfilled, (state, action) => {
          state.isLoading = false
          state.isSuccess = true
          state.cart = action.payload
          
        })
        .addCase(addToCart.rejected, (state) => {
          state.isLoading = false
          state.isError = true
        })  
  }
})

export const { reset } = cartSlice.actions
export default cartSlice.reducer

EDIT: stoje.js:

import { configureStore } from '@reduxjs/toolkit';
import cartReducer from '../features/cart/cart.slice'; // Your path to the slice

export const store = configureStore({
  reducer: {
    cart: cartReducer,
  },
});
Related