Uncaught TypeError: Cannot read properties of undefined (reading ‘map’)
import React, { useState } from "react";
import products from '../products'
function RecScreen() {
const [budget, setBudget] = useState(products);
const [items, setParts] = useState([]);
const handleInputChange = (event) => {
setBudget(event.target.value);
};
const handleSubmit = async (event) => {
event.preventDefault();
const response = await fetch(`/api/products?price=${budget}`);
const data = await response.json();
setParts(data.product);
};
return (
<div>
<h1>PC Parts Recommender</h1>
<form onSubmit={handleSubmit}>
<label>
Enter your budget:
<input type="number" value={budget} onChange={handleInputChange} />
</label>
<button className='btn btn-warning rounded ms-1' type="submit">Recommend Parts</button>
</form>
<ul>
{items.map(product => (
<li key={product.id}>{product.name} - ${product.price}</li>
))}
</ul>
</div>
);
}
export default RecScreen;
React code
In this code user enter budget and recommend pc parts but its show nothing and give this
Uncaught TypeError: Cannot read properties of undefined (reading ‘map’)
2
Answers
Here the prolem is that the property
product
does not exist in the objectdata
, however you are updating your stateitems
withdata.product
which isundefined
so when you try to map throughitems
usingitems.map
you are trying to map through anundefined
valueTo handle this use this code instead :
If data.product has a falsy value then in that case it will throw this error,you can modify this function like this