Thursday 5 September 2019

Bind event handler to document & have access to firebase api data via useEffect

Quick version:

My ultimate goal is to do something like the link below but with an async call to firebase per useEffect where the list data is composed of firebase object content.

https://codesandbox.io/s/usage-pxfy7

Problem

In the code below useEffect encapsulates code that pings firebase and gets some data back called "clients". The data is retrieved perfectly.

I then store that data using useState to two different instances of useState. The data is stored at clientList and clientListForRender.

So far so good.

Now the problem starts.

I have a third instance of useState that takes a number. I want to set a keypress event to the document so that I can use the up/down arrows to toggle the counter and access each value of the clientListForRender array.

When I set the eventListener I do not have access to the array (presumably due to the async calls not being in an order that allows for it).

I am not sure how to write my hooks in a way that gives me the result I want.

Thank you.

const clientsRef = firebase.database().ref('clients');
const [clientList,setClientListState] = useState([]);   
const [clientListForRender,setClientListStateForRender] = useState([]);
const [selectedIndex, updateSelectedIndex] = useState(0);



useEffect(() => {



  function handleKeyPress(event,arr){
    console.log(arr)
    if(event.key === "ArrowDown"){
      updateSelectedIndex((prev)=>{
          return prev += 1
      });
    }
  }



  clientsRef.on('child_added', snapshot => {
      const client = snapshot.val();
      client.key = snapshot.key;     //     __________________________1. get firebase data


     setClientListState(function(prev){       




           setClientListStateForRender(()=>[client,...prev]); //_______2 store data    



     // document.addEventListener('keydown', handleKeyPress);  <---I am not sure where to put this. I have experimented and 
                                                                   // I decided to omit my cluttered "experiments" to protect your eyes


           return[client,...prev]
      });

   });


},[]);



from Bind event handler to document & have access to firebase api data via useEffect

No comments:

Post a Comment