skip to Main Content

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


  1. 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 :

    import { useEffect, useState } from 'react'
    import '../adminInterface.css'
    import RecordList from './recordList'
    
    const Productsadmin = () => {
      const [records, setData] = useState([]) // Initialize to an empty array
    
      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.map((record) => (
              <RecordList key={record._id} record={record} />
            ))}
          </div>
        </div>
      )
    }
    
    export default Productsadmin
    
    Login or Signup to reply.
  2. 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.

    import { useEffect, useState } from 'react'
    import '../adminInterface.css'
    import RecordList from './recordList'
    
    const Productsadmin = () => {
      //set empty array
      const [records, setData] = useState([]) 
    
      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.length>0 ? 
                records.map((record) => (
                  <RecordList key={record._id} record={record} />
                )):
                  <p>No Record</p>
            }
          </div>
        </div>
      )
    }
    
    export default Productsadmin
    Login or Signup to reply.
  3. 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:

    1. for type safety, use an empty array for init: const [records, setData] = useState([]);
    2. for handling JSON data, please confirm it’s an Array, not an Object:
    if (data.ok && Array.isArray(json)) {
      setData(json);
    }
    

    Both of these are resolved in the example above with correct functionality.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search