How can I put dynamic category in react redux toolkit RTK?

Viewed 42

Error is Cannot read properties of undefined (reading 'category') I want to match my category on the product details page. But I can't able to implement it. I can't get the category I try a lot of ways. Please help me with how can I do it.

Redux says data: the actual response contents from the server. This field will be undefined until the response is received.

So how we can grab data?

Note: I use the Redux toolkit and RTK Query

I want to set my category chunk in my matchCategory state by default it is empty when the user click on the home page product button like ' View Detail' I want to match this id category and fetch all product to match the details category.

More Details

Remember I have a website My website has 20 product every product have two buttons one is add to cart and another one is View Details foe exmple You are a user you want to view product details before a product buy. Here is the main point I want to show a section that matches your product id category like electronics. You can call it a Related Product section :)

How can I do it?

My Product Details page

import React, { useEffect, useState } from "react";

import {
  useGetSingleProductQuery,
  useGetRelatedProductQuery,
  useGetAllProductsQuery,
} from "../../features/productsApi";

import { useParams } from "react-router-dom";
import axios from "axios";

function ProductDetails() {
  const { id } = useParams();

  const {
    data: getSingleProduct,
    isFetching,
    error,
  } = useGetSingleProductQuery(id);

// Here I can't access category
 const [matchCategory, setMatchCategory] = useState(getSingleProduct?.category);

  const url = `http://localhost:5000/products?category=${matchCategory}`;


  useEffect(() => {
    axios
      .get(url)
      .then((res) => {
        console.log(res.data)
        setMatchCategory(res.data)
      })
      .catch((err) => console.log(err));
  }, []);


  return (
    <div className="row mt-5">
      {isFetching ? (
        <p>Loading ...</p>
      ) : error ? (
        <p>Error occured</p>
      ) : (
        <>
          <div className="col-md-6 mb-5 text-center">
            <img
              className="w-100"
              style={{ height: "300px", objectFit: "contain" }}
              src={getSingleProduct.image}
              alt=""
            />
            <div>{getSingleProduct.title.substring(0, 20)}</div>
            <p>{getSingleProduct.description}</p>
             // But here we access in jsx :( how ?
            <p>{getSingleProduct.category}</p>
          </div>
        </>
      )}
    </div>
  );
}

export default ProductDetails;


1 Answers

I think the data object is undefined in the first time so you need to add a fallback or add the ? like this:

const [matchCategory, setMatchCategory] = useState(getSingleProduct?.category);
// or const [matchCategory, setMatchCategory] = useState(getSingleProduct.category ?? {});
Related