DEV Community

Omor Faruk
Omor Faruk

Posted on

The state in a React Redux e-commerce application

Image descriptionTo manage the state in a React Redux e-commerce application, you'll typically organize your state management to handle different aspects of the application, such as user authentication, products, cart, and orders. Here's a basic outline of how to set up Redux for an e-commerce app:

1. Setting Up Redux

  • Install the necessary packages:

     npm install redux react-redux @reduxjs/toolkit 

2. Define Your Slices

  • User Slice: Manages user authentication, profile, and other user-related data.
  • Products Slice: Handles the list of products, product details, and product filtering.
  • Cart Slice: Manages the shopping cart, including adding/removing items and updating quantities.
  • Orders Slice: Handles order creation, order history, and tracking.

3. Example Code for Slices

User Slice

import { createSlice } from '@reduxjs/toolkit'; const initialState = { isAuthenticated: false, user: null, }; const userSlice = createSlice({ name: 'user', initialState, reducers: { login(state, action) { state.isAuthenticated = true; state.user = action.payload; }, logout(state) { state.isAuthenticated = false; state.user = null; }, }, }); export const { login, logout } = userSlice.actions; export default userSlice.reducer; 
Enter fullscreen mode Exit fullscreen mode

Products Slice

import { createSlice } from '@reduxjs/toolkit'; const initialState = { products: [], loading: false, }; const productsSlice = createSlice({ name: 'products', initialState, reducers: { setProducts(state, action) { state.products = action.payload; }, setLoading(state, action) { state.loading = action.payload; }, }, }); export const { setProducts, setLoading } = productsSlice.actions; export default productsSlice.reducer; 
Enter fullscreen mode Exit fullscreen mode

Cart Slice

import { createSlice } from '@reduxjs/toolkit'; const initialState = { items: [], totalAmount: 0, }; const cartSlice = createSlice({ name: 'cart', initialState, reducers: { addItem(state, action) { const newItem = action.payload; const existingItem = state.items.find(item => item.id === newItem.id); if (!existingItem) { state.items.push({ ...newItem, quantity: 1 }); } else { existingItem.quantity += 1; } state.totalAmount += newItem.price; }, removeItem(state, action) { const id = action.payload; const existingItem = state.items.find(item => item.id === id); if (existingItem.quantity === 1) { state.items = state.items.filter(item => item.id !== id); } else { existingItem.quantity -= 1; } state.totalAmount -= existingItem.price; }, }, }); export const { addItem, removeItem } = cartSlice.actions; export default cartSlice.reducer; 
Enter fullscreen mode Exit fullscreen mode

4. Combine Reducers

  • Use combineReducers to combine the slices into a single root reducer.
 import { configureStore } from '@reduxjs/toolkit'; import userReducer from './userSlice'; import productsReducer from './productsSlice'; import cartReducer from './cartSlice'; const store = configureStore({ reducer: { user: userReducer, products: productsReducer, cart: cartReducer, }, }); export default store; 
Enter fullscreen mode Exit fullscreen mode

5. Provide the Store

  • Wrap your application with the Provider component from react-redux and pass the store to it.
 import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import store from './store'; import App from './App'; ReactDOM.render( <Provider store={store}> <App /> </Provider>,  document.getElementById('root') ); 
Enter fullscreen mode Exit fullscreen mode

6. Using Redux in Components

  • Use useSelector to access the state and useDispatch to dispatch actions.
 import React from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { addItem, removeItem } from './cartSlice'; const ProductList = () => { const products = useSelector(state => state.products.products); const dispatch = useDispatch(); const handleAddToCart = (product) => { dispatch(addItem(product)); }; return ( <div> {products.map(product => ( <div key={product.id}> <h3>{product.name}</h3>  <button onClick={() => handleAddToCart(product)}>Add to Cart</button>  </div>  ))} </div>  ); }; export default ProductList; 
Enter fullscreen mode Exit fullscreen mode

7. Middleware and Asynchronous Actions

  • Use Redux Thunk or Redux Toolkit's createAsyncThunk for handling asynchronous operations like fetching data from an API.

This setup provides a solid foundation for managing state in a React Redux e-commerce application, ensuring scalability and maintainability.

Top comments (0)