score:3

Accepted answer

Inside your functional components you can use the new useDispatch and useSelector features which is a easier to use.

Can you replace you CatalogProducts code with this, import the other necessary imports and try?

import React, { useEffect, useCallback } from "react";
import { useSelector, useDispatch } from "react-redux";
//other imports

const CatalogProducts = () => {
  const classes = useStyles();
  const dispatch = useDispatch();
  const products = useSelector(state => state.products);
  console.log("Products: ", products);

  const fetchProducts = useCallback(() => {
    dispatch(actions.getProductsAction());
  }, [dispatch]);

  useEffect(() => {
    fetchProducts();
  }, [fetchProducts]);

  const items = products.map((product, index) => {
    return (
      <Grid item xs={12} sm={6} md={3} key={index}>
        <CatalogProduct product={product} />
      </Grid>
    );
  });

  if (!products) {
    return <p>Loading ...</p>;
  } else if (products.length === 0) {
    return <div>No products found</div>;
  } else {
    return (
      <Container maxWidth="xl" className={classes.root}>
        <Grid
          container
          direction="row"
          justify="center"
          alignItems="center"
          spacing={3}
        >
          {items}
        </Grid>
      </Container>
    );
  }
};

export default CatalogProducts;

Sample codesandbox using jsonplaceholder fake api.


Related Query

More Query from same tag