I am facing an issue and i think a lot but not able to find any solution please help Note: I have removed some html code because i know the issue was not there So first let explain what the issue is i am desctructuring loading and product which take time to resolve initially when i first created it was not giving error loading become true and the loading component render as soon as the loading become false i can access the variable product and then render the data from it..but before some time i just add a feature of login and i have not even touch this page what happening now is until the value of product and loading is resolved the value of both variables is undefined i find it using console.log() using
import React,{useEffect} from "react";
import { getSingleProduct } from '../action/productAction'
import { useSelector,useDispatch } from 'react-redux'
import { Link } from "react-router-dom";
import { change_img } from "./main";
import { useParams } from "react-router-dom";
const ProductPage = () => {
const dispatch = useDispatch();
const {product,loading} = useSelector(state => state.productDetail)
let { id } = useParams();
console.log("The data of the product is",product)
console.log("The value of the laoding ",loading)
useEffect(()=>{
dispatch(getSingleProduct(id));
},[dispatch,id]);
var iloading =true;
return (
<>
{loading ? (
<h1>Loading...</h1>
) : (
<div>
<div className="card">
<div className="row no-gutters">
<aside className="col-md-6">
<h2 className="title">{product.name}</h2>
<div className="mb-3">
<var className="price h4">Price: $ {product.price}</var>
</div>
<p>
{product.description}
</p>
</main>
</div>
</div>
</div>
)}
</>
);
};
export default ProductPage;
CodePudding user response:
Looks like you are not formating the JSX in the return part Try this simplest form after imports :
const ProductPage = () => {
const dispatch = useDispatch()
const { product, loading } = useSelector((state) => state.productDetail)
let { id } = useParams()
useEffect(() => {
dispatch(getSingleProduct(id))
}, [dispatch, id])
return (
<>
{loading ? (
<h1>Loading...</h1>
) : (
<>
{' '}
<h2 className="title">{product.name}</h2>
</>
)}
</>
)
}
export default ProductPage
If that doesn't work then it means there is a problem in the getSingleProduct
or in the related reducer, If gives you the product name then means your code is not formatted correctly. Try to fix this then.
Edit: Also, I have noticed there is no handling if the server does not give the data or if loading and product are undefined then your component will also crash, You can handle this like :
<>
{loading ? (
<h1>Loading...</h1>
) : product ? (
<>
{' '}
<h2 className="title">{product.name}</h2>
</>
) : (
<> No data from Server</>
)}
</>