I'm building an e-commerce website and i'm trying to get an image data stored in MongoDB and must be rendered after fetching it with axios
.
The problem is that the image doesn't render at all, even thought in console i can see the product data alongside with img
data inside of it :
Console.dev: (URL: http://localhost:3000/product/62cc53596d10ae0a3c0af373
)
Object
product:
categories: (2) ['coat', 'women']
color: ['Yellow']
createdAt: "2022-07-11T16:44:09.859Z"
desc: "COTTON MINI RIPSTOP/ELASTHANE"
img: "https://www.pngarts.com/files/3/Women-Jacket-PNG-High-Quality-Image.png"
inStock: true
price: 70
size: (2) ['XL', 'M']
title: "Women Jacket"
updatedAt: "2022-07-11T16:44:09.859Z"
__v: 0
_id: "62cc53596d10ae0a3c0af373"
Network's tab shows no errors, and test with postman successfully gets all product's id data. Am i missing something which cause image doesn't render?
JSX code:
import { useEffect, useState } from "react";
import { publicRequest } from "../requestMethods";
//...
const Image = styled.img`
width: 100%;
height: 90vh;
object-fit: contain;
${mobile({ height: "40vh" })};
`;
//...
const Product = () => {
const location = useLocation();
const id = location.pathname.split("/")[2];
const [product, setProduct] = useState({});
useEffect(() => {
const getProduct = async () => {
try {
const res = await publicRequest.get("/products/find/" id);
setProduct(res.data);
console.log(res.data);
} catch (err) {}
};
getProduct();
}, [id]);
return (
<div>
<Container>
<Navbar />
<Annoncement />
<Wrapper>
<ImgContainer>
<Image src={product.img} />
</ImgContainer>
//...
RequestMethodes.js code:
import axios from "axios";
const BASE_URL = 'http://localhost:5000/api/';
const TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkXVCJ9.eyJpZCI6IjYyYzZmYWM2NWE0MzA2YWM4OGFljIzZCIsImlzQWRtaW4iOnRydWUsImlhdCI6MTY1NzczOTA5NCwiZXwIjoxNjY1NTE1MDk0fQ.DtQVQXrEeUMPFa6xvZQuHwh1FpOCbtYI_UEQTwhtRc";
export const publicRequest = axios.create({
baseURL: BASE_URL,
});
export const userRequest = axios.create({
baseURL: BASE_URL,
header: { token: `Bearer ${TOKEN}` }
});
Edit:
console.log(product.img)
after return
print undefined
.
CodePudding user response:
I fixed my own problem by changing <Image src={product.img} />
to <Image src={product?.product?.img} />
Check this MDN for more information about Optional chaining.