0

I create an e-commerce website with react, There is an error on redirecting between pages Problem: When wanted to redirect to SingleProduct Page from Category Page there's an error " Cannot read .map of undefined" but when refreshing the page, the page can be seen. Also, the same when want to redirect to the Home page from SingleProduct Page. The code below is from the Category Page . at usequery i use isloading and iserror and isSuccess in the return function as below

const {
    isLoading,
    isError,
    error,
    data: res,
    isSuccess,
  } = useQuery("product", () => Axios.get(`/Product/AllProduct`));
  
  
  // spinner when data loads
  if (isLoading) {
    return (
      <Col className="text-center" md="12">
        <div className="uil-reload-css reload-background mr-1 align-center">
          <div className="" />
        </div>
      </Col>
    );
  }
  if (isError) {
    return (
      <div>
        <h1 className="title text-center">
          {error.message}
          <br />
          <p className="error-msg text-center">
            We&apos;;re sorry, There is an error encounter.
            <br />
            Please retry again after few minutes.
          </p>
        </h1>
      </div>
    );
  }

 {isSuccess &&
          res.data.Result.map((product) => (
            <Col key={product.ID} md="4" sm="4">
              <Card className="card-product card-plain">
                <div className="card-image">
                  <img
                    alt={product.Name}
                    className="img-rounded img-responsive"
                    src={`/api/v1/ProductFile/${encodeURIComponent(
                      product.ID
                    )}/Product/${encodeURIComponent(product.ProductImages[0])}`}
                  />
              </Card>

enter image description here

2
  • Map only works on array types and not on any other types. Check once if you are using .map() on array only. Commented Aug 23, 2021 at 4:36
  • can you please share response structure here ? Commented Aug 23, 2021 at 4:39

2 Answers 2

1

Use conditional operator before map, like this:

{isSuccess && res && res.data && res.data.Result && res.data.Result.map((product) => (

Or optional chaining:

{isSuccess && res?.data?.Result?.map((product) => (
Sign up to request clarification or add additional context in comments.

Comments

0

In axios you can target the response by using res.data Maybe this is what you are missing out.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.