Skip to content

Instantly share code, notes, and snippets.

@femiabimbola
Last active April 17, 2023 12:14
Show Gist options
  • Save femiabimbola/594805e8703e0ce50f9e2958188750fc to your computer and use it in GitHub Desktop.
Save femiabimbola/594805e8703e0ce50f9e2958188750fc to your computer and use it in GitHub Desktop.
How to install and use redux toolkit

Install Redux toolkit

npx install @reduxjs/toolkit react-redux

Setup the store. The store can also be called state.

Create store.js at the root folder

The next line of code is for store.js

import { configureStore } from '@reduxjs/toolkit';

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

Connect the redux to your App.

The next line of code is for index.js

import { store } from './store'
import { Provider } from 'react-redux'

ReactDOM.render(
  <React.strictMode>
    <Provider store={store}>
      <App />
    <Provider />
  </React.strictMode />, document.getElementById('root'))

You may get error of no valid reducers

Setup the Slice also known as Feature

  • Create a Feature folder in the src Folder.

  • In the feature folder, Setup individual feature/slice

  • create feature\cartSlice.js

The next line of code is for cartSlice.js

import {createSice, createAsyncThunk} from '@reduxjs/toolkit'
const initialState = {
 cartItems: [],
 itemsCount: 0,
 total:0,
 isLoading: true }
 
 const cartSlice = createSlice({ name: 'cart', initialState })
 
 console.log(cartSlice)
 
 export default cartSlice.reducer;

Setup the reducer in the store.js

The next line of code is for store.js

import CartReducer from '/cartSlice.js'
import { configureStore } from '@reduxjs/toolkit';

export const store = configureStore({ 
                   reducer: { cart: CartReducer, modal},
                   });

Install Redux DevTools in your chrome extension

  • Store is seen as state. You will hardly use useState

Accessing data in the component

Create a Components folder and the Navbar Component

The code below is for Navbar component

import {useSelector} from 'react-redux'
const Navbar = () => {
  const {amount} = useSelector(state => state.cart)
  return (
    <p className=''> {amount} </p>
  }

Creating demo content to work with

Get in some value to the cart item create an array of cartitem

const cartItems = [
  {
  id: 'rec1JZlfCIBOPdcT2',
  title: 'Samsung Galaxy S8',
  price: '399.99',
  img: 'https://images2.imgbox.com/c2/14/zedmXgs6_o.png',
  amount: 1,
},
{
  id: 'recB6qcHPxb62YJ75',
  title: 'google pixel',
  price: '499.99',
  img: 'https://images2.imgbox.com/fb/3d/O4TPmhlt_o.png',
  amount: 1,
},
{
  id: 'recdRxBsE14Rr2VuJ',
  title: 'Xiaomi Redmi Note 2',
  price: '699.99',
  img: 'https://images2.imgbox.com/4f/3d/WN3GvciF_o.png',
  amount: 1,
},
{
  id: 'recwTo160XST3PIoW',
  title: 'Samsung Galaxy S7',
  price: '599.99 ',
  img: 'https://images2.imgbox.com/2e/7c/yFsJ4Zkb_o.png',
  amount: 1,
},]

export default cartItems

Import the array into the cartslice.

  import cartItems from '../../cartitems'
  import {createSice, createAsyncThunk} from '@reduxjs\toolkit'
 
 const initialState = {
  cartItems: cartItems,
  itemsCount: 0,
  total:0,
  isLoading: true }
 

Create cartcontainer.js

  • CartContainer should be created before creating individual cart
import CartItem from './CartItem';
import { useDispatch, useSelector } from 'react-redux';
import { openModal } from '../features/modal/modalSlice';

const CartContainer = () => {
 const dispatch = useDispatch();
 const { cartItems, total, amount } = useSelector((store) => store.cart);

 if (amount < 1) {
   return (
     <section className='cart'>
       <header>
         <h2>your bag</h2>
         <h4 className='empty-cart'>is currently empty</h4>
       </header>
     </section>
   );
 }

 return (
   <section className='cart'>
     <header>
       <h2>your bag</h2>
     </header>
     <div>
       {cartItems.map((item) => {
         return <CartItem key={item.id} {...item} />;
       })}
     </div>
     <footer>
       <hr />
       <div className='cart-total'>
         <h4>
           total <span>${total.toFixed(2)}</span>
         </h4>
       </div>
       <button className='btn clear-btn' onClick={() => dispatch(openModal())}>
         clear cart
       </button>
     </footer>
   </section>
 );
};
export default CartContainer;

Manipulating the State

This is for manipulating the state in cartslice

import {createSice, createAsyncThunk} from '@reduxjs\toolkit'
const initialState = {
 cartItems: [],
 itemsCount: 0,
 total:0,
 isLoading: true }
 
 const cartSlice = createSlice({ 
                     name: 'cart', initialState,
                     reducers:{
                      clearCart: (state) => { state.cartItems = []; }
                     }
                   })
 
 console.log(cartSlice)
 
 export const {clearCart} = cartSlice.actions;
 
 export default cartSlice.Reducer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment