Reputation: 217
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';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>
Upvotes: 0
Views: 98
Reputation: 79
In axios you can target the response by using res.data
Maybe this is what you are missing out.
Upvotes: 0
Reputation: 190
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) => (
Upvotes: 1