skip to Main Content

I receive data in react using axios but when i try to map through it i get an error "Cannot read properties of undefined (reading ‘map’)" I was trying to find solutions to this and i think that react first renders the page before setting the data, I also tried looping thorugh the data manually or using forEach but still got a variation of the errors below.
For some reason it also returns 3 similar errors every time it runs

Code:

import axios from "axios";

function Table() {

let [backendData, setData] = useState();


async function getData(){
  await axios.get("table")
  .then(response => response.data)
  .then(data => setData(data))
}

useEffect(() => {
getData();
}, [])





return(
  <div>
    <table>
      <thead>
        <tr>
          <th>Child's Name</th>
          <th>Child's Age</th>
          <th>Room No.</th>
          <th>Parent/Guardian Location</th>
          <th>Parent/Guardian Signature In</th>
          <th>Staff Signature In</th>
          <th>Parent/Guardian Signature Out</th>
          <th>Staff Signature Out</th>
        </tr>
      </thead>

            {backendData.map(child => {
              <tr key={child._id}>
                <td>{child.childName}</td>
                <td>{child.childAge}</td>
                <td>{child.roomNumber}</td>
                <td>temporary</td>
                <td><img src={child.parentSignature} /></td>
                <td><img src={child.parentSignature} /></td>
                <td><img src={child.parentSignature} /></td>
                <td><img src={child.parentSignature} /></td>
              </tr> 
            })}

    </table>
  </div>
  ) 

}

export default Table;

Error:

Cannot read properties of undefined (reading 'map')
TypeError: Cannot read properties of undefined (reading 'map')
   at Table (http://localhost:3000/static/js/bundle.js:2183:29)
   at renderWithHooks (http://localhost:3000/static/js/bundle.js:24189:22)
   at mountIndeterminateComponent (http://localhost:3000/static/js/bundle.js:27475:17)
   at beginWork (http://localhost:3000/static/js/bundle.js:28771:20)
   at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:13781:18)
   at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:13825:20)
   at invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:13882:35)
   at beginWork$1 (http://localhost:3000/static/js/bundle.js:33756:11)
   at performUnitOfWork (http://localhost:3000/static/js/bundle.js:33003:16)
   at workLoopSync (http://localhost:3000/static/js/bundle.js:32926:9)
ERROR
Cannot read properties of undefined (reading 'map')
TypeError: Cannot read properties of undefined (reading 'map')
   at Table (http://localhost:3000/static/js/bundle.js:2183:29)
   at renderWithHooks (http://localhost:3000/static/js/bundle.js:24189:22)
   at mountIndeterminateComponent (http://localhost:3000/static/js/bundle.js:27475:17)
   at beginWork (http://localhost:3000/static/js/bundle.js:28771:20)
   at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:13781:18)
   at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:13825:20)
   at invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:13882:35)
   at beginWork$1 (http://localhost:3000/static/js/bundle.js:33756:11)
   at performUnitOfWork (http://localhost:3000/static/js/bundle.js:33003:16)
   at workLoopSync (http://localhost:3000/static/js/bundle.js:32926:9)
ERROR
Cannot read properties of undefined (reading 'map')
TypeError: Cannot read properties of undefined (reading 'map')
   at Table (http://localhost:3000/static/js/bundle.js:2183:29)
   at renderWithHooks (http://localhost:3000/static/js/bundle.js:24189:22)
   at mountIndeterminateComponent (http://localhost:3000/static/js/bundle.js:27475:17)
   at beginWork (http://localhost:3000/static/js/bundle.js:28771:20)
   at beginWork$1 (http://localhost:3000/static/js/bundle.js:33734:18)
   at performUnitOfWork (http://localhost:3000/static/js/bundle.js:33003:16)
   at workLoopSync (http://localhost:3000/static/js/bundle.js:32926:9)
   at renderRootSync (http://localhost:3000/static/js/bundle.js:32899:11)
   at recoverFromConcurrentError (http://localhost:3000/static/js/bundle.js:32391:24)
   at performConcurrentWorkOnRoot (http://localhost:3000/static/js/bundle.js:32303:26)```

4

Answers


  1. This is happening because your backendData variable has an initial value of undefined. React useState() hook accepts a parameter, which will be set as the initial value for the state variable.

    Currently in your code, your react component will attempt to return your jsx even before your useEffect finishes your axios request. Since you aren’t passing an initial value to your useState() hook, your backendData variable has an undefined value initially. And when trying to access the .map() function that you would use on an array, there is no such method that exists for your undefined data type.

    Instead, do

    const [backendData, setData] = useState([]);
    

    This’ll set the initial value of backendData to an empty array. And when your backendData.map() function runs now, there will be no error because there is now an empty array to map over.

    Login or Signup to reply.
  2. This is because the below code (map )in JSX runs before the response of API. So you can resolve it by putting ? before map. Like this

     {backendData?.map(child => {
              <tr key={child._id}>
                <td>{child.childName}</td>
                <td>{child.childAge}</td>
                <td>{child.roomNumber}</td>
                <td>temporary</td>
                <td><img src={child.parentSignature} /></td>
                <td><img src={child.parentSignature} /></td>
                <td><img src={child.parentSignature} /></td>
                <td><img src={child.parentSignature} /></td>
              </tr> 
            })}
    

    OR

     {backendData?.length > 0 && backendData.map(child => {
              <tr key={child._id}>
                <td>{child.childName}</td>
                <td>{child.childAge}</td>
                <td>{child.roomNumber}</td>
                <td>temporary</td>
                <td><img src={child.parentSignature} /></td>
                <td><img src={child.parentSignature} /></td>
                <td><img src={child.parentSignature} /></td>
                <td><img src={child.parentSignature} /></td>
              </tr> 
            })}
    
    Login or Signup to reply.
  3. On the first render, the effect has not run yet, so backendData is the inital value passed to useState: undefined, in this case.

    The component tries to call map on undefined, which causes the error.

    To fix this, you could set the initial state to an empty array

    const [backendData, setData] = useState([]);
    

    or use optional chaining to avoid calling map and immediately return undefined when backendData is undefined. Note that you should not use curly braces in order to directly return the JSX from map.

    {backendData?.map(child => (
      <tr key={child._id}>
        <td>{child.childName}</td>
        <td>{child.childAge}</td>
        <td>{child.roomNumber}</td>
        <td>temporary</td>
        <td><img src={child.parentSignature} /></td>
        <td><img src={child.parentSignature} /></td>
        <td><img src={child.parentSignature} /></td>
        <td><img src={child.parentSignature} /></td>
      </tr> 
    ))}
    
    Login or Signup to reply.
  4. When rendering your backendData state with the "map" method you’re assuming you’re reading through an array or a list. But you’re declaring a state with an initial value of undefined.

    An easy fix to this issue would be redeclaring your state as follows:

    const [backendData, setData] = useState([]);
    

    Instead of:

    let [backendData, setData] = useState();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search