skip to Main Content

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


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

    Login or Signup to reply.
  2. 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.

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