Meli497
Meli497

Reputation: 53

Get Firestore Data based on User Input

I am creating a React App which will be used to display Dynamic Maps for DnD (vid files). Based on the User Input in a select field, a video player will get the specific video file from the firebase firestore, where I store the video files.

const Streamplayer = ({vidSelection}) => { //vidSelection is the event.target.value from the Select Input Field (basically a String)

const [links, setLinks] =  useState([])

console.log(vidSelection);
useEffect(() => {
   getLinks()
}, [])

useEffect(() => {
   console.log(links)
}, [links])

function getLinks(){
   const vidRef = collection(db, 'links');
   getDocs(vidRef).then(response => {
      console.log(response.docs)
      const lnks = response.docs.map(doc => ({
         data: doc.data(), 
         id: doc.id,
      }))
      setLinks(lnks)
   }).catch(error => console.log(error.message));
}

function getVid(){
   const toReturn = links.map((link) => link.data.vidSelection);//I want to change whatever gets returned based on input
   console.log(toReturn)
   return toReturn;
}

return (    
<video
controls={false}
autoPlay
muted
loop
className="Video"
key={getVid()}
>
<source src={getVid()} type="video/mp4" />
</video>
)
}

export default Streamplayer

So in the method getVid() I request the data stored in the Firebase Firestore "Links" Collection and I want to change whichever I get based on the userInput. So if the User chooses the map "Grotto", I want to make the call "link.data.grotto". But since vidSelection is a String, I can't simply insert it in this call. Any Ideas how to solve this?

Upvotes: 1

Views: 154

Answers (1)

Nathan
Nathan

Reputation: 78419

You can make useEffect get re-called when props change, by providing the prop in the dependency list for useEffect. Simply change your first useEffect call to:

useEffect(() => {
   getLinks()
}, [vidSelection])

When the selection changes, useEffect will fire and call getLinks, which will update your state.

(Also, minor suggestion: remove the getVid() function, and just set a const videoSource = links.map((link) => link.data.vidSelection) in the function body. Right now you're calling the function twice which will cause the mapping to happen twice, and I think it's generally clearer to have consts flow directly from state, makes it easier to reason about state.)

Upvotes: 1

Related Questions