Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Cannot read properties of undefined (reading 'map') error in MERN stack project
In my project, I try to fetch data from the backend to display in the frontend using fetch API. Each time I do this I get Cannot read properties of undefined (reading 'map') error. When I check the console, I get a fulfilled promise.
I console.log the setState function to see what data is logged there but it returned undefined. why is my setState undefined?
In my backend, data displays fine when I test on thunder client in vscode. I also paste http://localhost:8080/data' in chrome and it also works.
why is data undefined?
//parent component
const Shopstore = () => {
const [dataProducts, setData ] = useState([])
const url = 'http://localhost:8080/data'
useEffect(()=> {
const fetchfunc = async ()=> {
try {
const response = await fetch(url)
if(!response.ok){
throw new Error("network issues pls wait ");
}
const data = await response.json()
//this console.log returns a fulfilled promise
console.log(data)
//this console.log part returns undefined
console.log( setData( data.dataProducts ));
} catch (error) {
console.log('error', error)
}
}
fetchfunc()
}, [] )
return (
<div className='Shopstore mt-5'>
<Container>
<Row>
<Col md={10} className='big mt-3'>
{ dataProducts ? dataProducts.map((product)=> {
return(
<Listings key={product._id } { ... product } />
)
}) : <p>no data</p> }
</Col>
</Row>
</Container>
</div>
)
}
export default Shopstore
//child component
const Listings = (products) => {
const { image, heading, price, _id } = products
return (
<div className='listings mt-3 mb-3'>
<Container>
<Row>
<Col md={4} id = { _id }>
<div className="card mx-auto" style={{width: '250px'}}>
<Card>
<div className='image mx-auto '>
<Link to={ `/shop/${products._id}` }> <img src={image} alt="" className='img-fluid' style={{width: '300px'}} /> </Link>
<CardBody>
<div className='title'>
<h5>{heading}</h5>
</div>
<div className='price'>
<span>{price}</span>
</div>
<div className=' mx-auto' >
<button className='mx-auto cartbutton' >Add to cart</button>
</div>
</CardBody>
</div>
</Card>
</div>
</Col>
</Row>
</Container>
</div>
)
}
export default Listings
The ternary operator triggers no data as there is no data to display.
0 comment threads