Home > Software engineering >  How to display an array in JSX from a function in React?
How to display an array in JSX from a function in React?

Time:07-13

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);
  });
}

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

Also, you allDocs array is defined as const so you cant really pish values in and out of it. Try declaring it as let. Moreover, you should use the for…in.. loop coz that is what will let you loop synchronously and give your desired results, instead of the forEach loop whose code runs asynchronously.

  • Related