Home > other >  Can't connect redux and React to create and delete products
Can't connect redux and React to create and delete products

Time:07-06

I am learning react and redux and building simple product delete and create. I already define actions.js, Basket.js, index.js and reducer.js. here is the codes

The basket component is already implemented and working as expected. Your task is to connect it with the Redux store and pass three props: products, totalPrice and an on onRemove handler:

products should be the list of products taken directly from the store

totalPrice should be calculated based on the list of products

onRemove is a handler accepting a productId parameter, and should dispatch the removeProductFromBasket action.

index.js

import { combineReducers, createStore } from "redux";
import React from "react";
import ReactDOM from "react-dom";
import { connect, Provider } from "react-redux";

import basketReducer from "./reducer";
import Basket from "./Basket";
import { addProductToBasket } from "./actions";

const rootReducer = combineReducers({
  basket: basketReducer,
});

const store = createStore(rootReducer);

function getSampleProduct() {
  return {
    id: Math.floor(Math.random() * 10000000),
    name: "product 1",
    quantity: 1,
    price: 1.0,
  };
}

function AddProductComponent({ addProduct }) {
  return <button onClick={() => addProduct(getSampleProduct())}>Add product to basket</button>;
}

const AddProduct = connect(null, (dispatch) => ({
  addProduct: (product) => dispatch(addProductToBasket(product)),
}))(AddProductComponent);

ReactDOM.render(
  <Provider store={store}>
    <Basket />

    <div id="utils">
      <AddProduct />
    </div>
  </Provider>,
  document.getElementById("root")
);

action.js

export function addProductToBasket(product) {
  return {
    payload: product,
    type: "ADD_PRODUCT_TO_BASKET",
  };
}

export function removeProductFromBasket(productId) {
  return {
    payload: { productId },
    type: "REMOVE_PRODUCT_FROM_BASKET",
  };
}

Basket.js

import React from "react";
import { connect } from "react-redux";
import { removeProductFromBasket } from "./actions";

// You can use console.log for debugging purposes.

// This component is already implemented and working as expected.
// `Please focus on Redux related parts.
export function Basket({ products = [], onRemove, totalPrice = 0.0 }) {
  return (
    <div>
      <ul className="products">
        {products.map((product) => (
          <li key={product.id} id={product-${product.id}}>
            <span>Name: {product.name}</span>
            <span>Quantity: {product.quantity}</span>
            <button
              id={remove-${product.id}}
              onClick={() => onRemove(product.id)}
            >
              Remove
            </button>
          </li>
        ))}
      </ul>
      <div>
        Total price: <span id="total-price">{totalPrice}</span>
      </div>
    </div>
  );
}

function mapStateToProps(state) {
  return {};
}

function mapDispatchToProps(dispatch) {
  return {};
}

export default connect(mapStateToProps, mapDispatchToProps)(Basket);

reducer.js

import React from "react";
import { connect } from "react-redux";
import { removeProductFromBasket } from "./actions";

// You can use console.log for debugging purposes.

// This component is already implemented and working as expected.
// `Please focus on Redux related parts.
export function Basket({ products = [], onRemove, totalPrice = 0.0 }) {
  return (
    <div>
      <ul className="products">
        {products.map((product) => (
          <li key={product.id} id={product-${product.id}}>
            <span>Name: {product.name}</span>
            <span>Quantity: {product.quantity}</span>
            <button
              id={remove-${product.id}}
              onClick={() => onRemove(product.id)}
            >
              Remove
            </button>
          </li>
        ))}
      </ul>
      <div>
        Total price: <span id="total-price">{totalPrice}</span>
      </div>
    </div>
  );
}

function mapStateToProps(state) {
  return {};
}

function mapDispatchToProps(dispatch) {
  return {};
}

export default connect(mapStateToProps, mapDispatchToProps)(Basket);

The basket component is already implemented and working as expected. Your task is to connect it with the Redux store and pass three props: products, totalPrice and an on onRemove handler:

products should be the list of products taken directly from the store

totalPrice should be calculated based on the list of products

onRemove is a handler accepting a productId parameter, and should dispatch the removeProductFromBasket action.

CodePudding user response:

If you are using functional component, then use

  • useSelector to get store data
  • useDispatch to dispatch the action

Please, install react-redux for the same. It will be easy to understand! Still, getting error then we can look into another cause.

Best of luck! Happy coding...

CodePudding user response:

Use react hooks in order to make your changes visible by re-rendereing it on the page.

  • Related