DEV Community

tjray-dev
tjray-dev

Posted on

fetch 2: asynchronous boogaloo

using javascript async and await to fetch from an api

by using the async and await keywords in javascript we can write fetch functions that are cleaner and easier to read by getting rid of the train of .then() and the possible confusion stemming from nested functions

allowing this:

    fetch(`http://localhost:9292/battle/${battle.id}`, {
              method: 'PATCH',
              headers: {
                'Content-Type' : 'application/json'

              },
              body: ""
      }).then(r => r.json())
          .then("do a thing with the data")
Enter fullscreen mode Exit fullscreen mode

to become this:

async function round(){
      // Here we assign the return value of the fetch to a variable
      const response =  await fetch(`http://localhost:9292/battle/${battle.id}`, {
              method: 'PATCH',
              headers: {
                'Content-Type' : 'application/json'

              },
              body: ""
      })
      // Here we assign the return value of the .json() call on response to a variable
      const roundResult  = await response.json()
      // here we return the value of calling setBattle (a react state setter function) with an argumant of roundResult declared above
      return setBattle(roundResult)
    }
Enter fullscreen mode Exit fullscreen mode

Using setTimeout to delay a method call

setTimeout is a built in javascript method that allows for the delaying of an action by a specific length of time expressed in milliseconds. By passing it an action to perform, in our case the async fetch above, and a time you can pace the fetches of your app allowing for an entirely new level of dynamism to it.

to illustrate:

async function round(){
      // Here we assign the return value of the fetch to a variable
      const response =  await fetch(`http://localhost:9292/battle/${battle.id}`, {
              method: 'PATCH',
              headers: {
                'Content-Type' : 'application/json'

              },
              body: ""
      })
      // Here we assign the return value of the .json() call on response to a variable
      const roundResult  = await response.json()
      // here we return the value of calling setBattle (a react state setter function) with an argument of roundResult declared above
      return setBattle(roundResult)
    }
setTimeout(round, 2000)
Enter fullscreen mode Exit fullscreen mode

here we see our async function from above being passed in as the callback to our setTimeout function along with a time of 2000 milliseconds.

using React's useEffect hook to loop asynchronously on a delay

By placing the above code into a useEffect hook and syncing that useEffect to the state being changed, as depicted, we can loop on a timer essentially. This, when coupled with an api that return an ever decreasing number that can be evaluated by the client allows for a kind of cross network while loop that can be controlled by the changing of data on the server.

Like so:

  useEffect(() => {
    async function round(){
      // Here we assign the return value of the fetch to a variable
      const response =  await fetch(`http://localhost:9292/battle/${battle.id}`, {
              method: 'PATCH',
              headers: {
                'Content-Type' : 'application/json'

              },
              body: ""
      })
      // Here we assign the return value of the .json() call on response to a variable
      const roundResult  = await response.json()
      // here we return the value of calling setBattle (a react state setter function) with an argument of roundResult declared above
      return setBattle(roundResult)
    }
    setTimeout( round, 2000)
  }, [battle])
Enter fullscreen mode Exit fullscreen mode

This will of course loop infinitely if not properly handled on either the server or client side, and as such all the usual disclaimers apply.

Top comments (0)