const Productabout = () => {
const params = useParams();
const [singleProduct, setsingleProduct] = useState()
const host = "http://localhost:5000"
useEffect(() => {
if (params.id) {
getproduct()
}
}, [params.id])
console.log(singleProduct.name);
getting error like Cannot read properties of undefined (reading ‘name’)
2
Answers
This is practically a situtation where a loading element should be rendered first, until your asynchronous
getProduct
function fetches the product from the API and sets yoursingleProduct
state to it.Here is a very simplified version of how you could implement that. Many other implementations can be done:
Set a default value for
singleProduct
. In this case, I’m setting it to undefined.Now, we can check for the value of
singleProduct
. If it’sundefined
, that means that thegetProduct
function did not finish executing yet and that we should display a loading element instead. When it’s finished executing, the value ofsingleProduct
would change fromundefined
to some object like{ "name": "hello world" }
. In that case we can safely display the product:At the first render, the
singleProduct
is set toundefined
.So when the
console.log(singleProduct.name)
is called during the initial rendering, it will raise an error because it’s attempting to access thename
property of undefinedsingleProduct
.If you want to monitor the
singleProduct
state, simply use auseEffect
block where you can log thename
ofsingleProduct
while it’s available.Or, if you are too lazy to use
useEffect
, you can simply use something like this:or you can use the optional chaining operator (?.) if you are using ECMAScript 2020 (ES11).