I’m working on a personal project using MERN Stacks, and I really can’t prevent this error when trying to load Mongodb data
Uncaught TypeError: records.map is not a function
I’m trying to display data that is in the the database into my view that’ll display then in the admin interface this is how the full view’s code look like:
import { useEffect , useState } from 'react'
import '../adminInterface.css'
import RecordList from './recordList'
const Productsadmin = () => {
const [records, setData] = useState(null)
useEffect(() => {
const fetchdata = async () => {
const data = await fetch('http://localhost:5000/api/getproducts/')
const json = await data.json()
if (data.ok) {
setData(json)
}
}
fetchdata()
},[])
return (
<div className='main-page'>
<img className='logo-admin' src='https://i.imgur.com/v10SbL4.png'></img>
<div className='productsdata'>
{records && records.map((record) => (
<RecordList key={record._id} record={record} />
))}
</div>
</div>
)
}
export default Productsadmin
and here’s the recordlist.js code
const RecordList = ({ record }) => {
return (
<div className="record-details">
<h4>{record.productName}</h4>
<p><strong>Location : </strong>{record.location}</p>
<p><strong>Photo : </strong>{record.photo}</p>
</div>
)
}
export default RecordList
also I’ve tried to log the data before trying to render it, and it works perfectlly
3
Answers
In order to work correctly, you should initialize your records variable to an empty array, so that you could then use the map() method on it :
You need to set initial state value as blank array as like
const [records, setData] = useState([])
then you can run your code.
I have also handled the error if Array is empty then it’s showing No Record message.
There are two errors in your code. Please check this Expo Snack (for RN, but same logic): https://snack.expo.dev/@zvona/async-fetch
I’ll elaborate:
const [records, setData] = useState([]);
Both of these are resolved in the example above with correct functionality.