Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React component with async array not updating

I have a component that gets an array of objects from a database using an async – await function. When the function gets the data and sets the array to a State variable, the component doesn’t seem to update and I get errors about being unable to read properties. The data is being retrieved from the database correctly because I can console.log it. What am I doing wrong?

export default function LevelLeaderboard ({ level }) {
  const [leaderboardData, setLeaderboardData] = useState([])

  useEffect(()=>{
    getLeaderBoardData(level)
    .then((data)=>{
      console.log(data)
      setLeaderboardData(data)
    })
  },[level]);

  return (
    <div id="level" className="level-leaderboard">
      <ul>
      <li>{leaderboardData[0]['name']}</li>
      </ul>
    </div>       
  )
}

Error:

LevelLeaderboard.js:19 Uncaught TypeError: Cannot read properties of undefined (reading ‘0’)
at LevelLeaderboard (LevelLeaderboard.js:19:1)
at renderWithHooks (react-dom.development.js:16305:1)
at mountIndeterminateComponent (react-dom.development.js:20074:1)
at beginWork (react-dom.development.js:21587:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at beginWork$1 (react-dom.development.js:27451:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here’s the async function:

export async function getLeaderBoardData(level, handleData){
  const querySnapshot = await getDocs(collection(leaderboard, level));
  let tempArr = [];
  querySnapshot.forEach((doc) => {
    tempArr.push(doc.data())
  });
  return tempArr;
}

>Solution :

You should add a conditional rendering to

<li>{leaderboardData[0]['name']}</li>

something like:

{leaderboardData.length >= 1 && <li>{leaderboardData[0]['name']}</li>}

since the array ‘leaderboardData’ its empty when component first render

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading