How to display an array in JSX from a function in React?

Viewed 56

I implemented a function where I fetch all Docs from a Firebase collection on a click.

Now I want to display each doc I fetched in a <div> container in JSX. When I try to take the array and display it, I´m getting the error that the array is not found.

This is my code:

async function getAllDivs(){
  const querySnapshot = await getDocs(collection(db, "Div"))
  const allDivs = [];
  querySnapshot.forEach(doc => {
    allDivs.push(doc.data().DivContent);
  });
}
2 Answers

You would have to return the array from the function, because of the "scope".

Example:


//your current function
async function getAllDivs(){
  const querySnapshot = await getDocs(collection(db, "Div"));
  return querySnapshot.map((doc) => doc.data().DivContent);
}

//your component
let divs = getAllDivs(); //you can now use "divs" in this scope

return (
    <>
        divs.map((current_div) => { <div>{current_div}</div> })
    </>
) 

Also, I suggest against pushing data to an array labeled as const, as it could be confusing for someone else reading your code.

I think you could use something like this:

const MyComponent = () => {
  const [docs, setDocs] = useState();

  const onClickHandler = async () => {
    const docs = await getDocs(collection(db, "Div"));

    setDocs(docs);
  }
    
  return (
    <>
      <button onClick={onClickHandler}>Get docs</button>
      {docs && docs.map(doc => (
        <div>{doc.data().DivContent}</div>
      ))}
    </>
  )
}

If DivContent contains HTML you can use dangerouslySetInnerHTML.

Related