Setup redux JS
installation
npm install react-redux
in Index file you should import "Provider" and wrapp the app component, then we pass the store as props:
import React from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App";
import { store } from "./store";
import { Provider } from "react-redux";
const container = document.getElementById("root");
const root = createRoot(container);
root.render(
<Provider store={store}>
<App />
</Provider>
);
Now we must create a Js file let's say CartSlice , ItemSlice ....
we used createSlice function to create like a new object named 'cart' then we passed the initialState object as second parameter .
import { createSlice } from "@reduxjs/toolkit";
import cartItems from "../../cartItems";
const initialState = {
cartItems: cartItems,
amount: 1,
total: 0,
isLoading: true,
};
const cartSlice = createSlice({
name: "cart",
initialState,
});
// console.log(cartSlice);
export default cartSlice.reducer;
Now if we want to use the variable here we can by using useSelector function , for example:
import { CartIcon } from "../icons";
import { useSelector } from "react-redux";
import React from "react";
const Navbar = () => {
const amount = useSelector((store) => store.cart.amount);
return (
<nav>
<div className="nav-center">
<h3>redux toolkit</h3>
<div className="nav-container">
<CartIcon />
<div className="amount-container">
<p className="total-amount">{amount}</p>
</div>
</div>
</div>
</nav>
);
};
export default Navbar;
now if we want to define any function we can define it in the reducers then export it
import { createSlice } from "@reduxjs/toolkit";
import cartItems from "../../cartItems";
const initialState = {
cartItems: cartItems,
amount: 1,
total: 0,
isLoading: true,
};
const cartSlice = createSlice({
name: "cart",
initialState,
reducers: {
clearCart: (state) => {
state.cartItems = [];
},
},
});
export const { clearCart } = cartSlice.actions;
// console.log(cartSlice);
export default cartSlice.reducer;
and to invoke it we must use useDispatch function
import React from "react";
import CartItem from "./CartItem";
import { useSelector, useDispatch } from "react-redux";
import { clearCart } from "../features/cart/CartSlice";
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}</span>
</h4>
</div>
<button
className="btn clear-btn"
onClick={() => {
dispatch(clearCart());
}}
>
clear cart
</button>
</footer>
</section>
);
};
export default CartContainer;