How do I apply Redux in Add-to-Cart?

How do I apply Redux in Add-to-Cart?

Implementing Redux in a shopping cart scenario involves managing the cart's state in a centralized store. Here's a simplified example of how you can use Redux to handle adding items to a shopping cart:

  1. Install the necessary packages:
npm install redux react-redux
  1. Create actions, reducers, and stores:
// actions.js
export const addToCart = (item) => ({
  type: 'ADD_TO_CART',
  payload: item,
});

// reducers.js
const initialState = {
  cartItems: [],
};

const cartReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'ADD_TO_CART':
      return {
        ...state,
        cartItems: [...state.cartItems, action.payload],
      };
    default:
      return state;
  }
};

export default cartReducer;
  1. Create the Redux store:
// store.js
import { createStore } from 'redux';
import cartReducer from './reducers';

const store = createStore(cartReducer);

export default store;
  1. Integrate with the React component.
// ShoppingCart.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { addToCart } from './actions';

const ShoppingCart = () => {
  const cartItems = useSelector((state) => state.cartItems);
  const dispatch = useDispatch();

  const handleAddToCart = (item) => {
    dispatch(addToCart(item));
  };

  return (
    <div>
      <h2>Shopping Cart</h2>
      <ul>
        {cartItems.map((item, index) => (
          <li key={index}>{item.name}</li>
        ))}
      </ul>
      <button onClick={() => handleAddToCart({ id: 1, name: 'Product A' })}>
        Add Product A to Cart
      </button>
      <button onClick={() => handleAddToCart({ id: 2, name: 'Product B' })}>
        Add Product B to Cart
      </button>
    </div>
  );
};

export default ShoppingCart;
  1. Use the Redux store in your main application file:
// App.js
import React from 'react';
import { Provider } from 'react-redux';
import store from './store';
import ShoppingCart from './ShoppingCart';

const App = () => {
  return (
    <Provider store={store}>
      <div>
        <h1>Redux Shopping Cart Example</h1>
        <ShoppingCart />
      </div>
    </Provider>
  );
};

export default App;

In this example, theaddToCart action is dispatched when a user clicks the "Add to Cart" button. The cartReducer handles this action and updates the state by adding the item to the cartItems array. The ShoppingCart component connects to the Redux store using the useSelector hook and displays the items in the shopping cart. The Provider component from react-redux is used to wrap the main application, providing access to the Redux store for all components.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!