skip to Main Content

I have a collection in firebase called "polls". The collection is an array, and within the array I have 4 urls (url_a, url_b, url_c, and url_d). I want to pull these urls out of the array in my react app so I can use them as the src for 4 different images.

I know since "polls" is an array, I can’t just pull the urls directly by setting some variable to "polls.data.url_a". With the 2nd useEffect function in the code below, I’m able to console.log the array
and the data within it using forEach. I can console.log poll.data, and even poll.data.url_a and it returns the proper result.

But I am stuck on how to get outside of that forEach and actually capture the individual urls to where I can assign them to a variable so I can make use of them.

import { useEffect, useState } from "react"
import { collection, getDocs } from "firebase/firestore"
import { db } from '../firebase.config'


function Food() {
  const [polls, setPolls] = useState([])


  useEffect(() => {
    getPolls()
  }, [])


 ** useEffect(() => {
    polls.forEach((poll) => 
    console.log(poll.data.url_a))
}, [polls])
**
function getPolls() {

    const pollsRef = collection(db, 'polls');
    
   getDocs(pollsRef).then(response => {
      const poll = response.docs.map(doc => ({data: doc.data(), id: doc.id}))
      setPolls(poll)
    }).catch(error => console.log(error.message))
  
  }
  
  return (
    <div>
      Food
    </div>
  )
}

export default Food

I’ve tried setting a variable within the forEach and calling it later, and running a forEach later on in the function. But I just don’t know how to get to the URL in a usable way, outside of just console logging it. Any help would be greatly appreciated, thanks!

2

Answers


  1. Check out what Renaud suggested here to see how to assign variables: Get Firebase Collection into simple array

    If I understand what you’re asking, you’ll need the poll const to instead point towards a global store variable or to reference it within the template section.

    Login or Signup to reply.
  2. If the data your fetching is structured like this:

    const polls = [{
      data: {
        url_a: "url a",
        url_b: "url b"
      }
    }]

    It’s easier to just assign it to an object state variable instead of an array.

    const [polls, setPolls] = useState({})
    // ...
    useEffect(() => {
      getPolls()
    }, [polls])
    
    function getPolls() {
    
      const pollsRef = collection(db, 'polls');
    
      getDocs(pollsRef).then(response => {
        const polls = response.docs.map(doc => ({data: doc.data(), id: doc.id}))
        polls.map(poll => setPolls(poll.data))
      }).catch(error => console.log(error.message))
    }
    // ...
      return <img src={polls.url_a} alt="" />
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search