Using Redux-Thunk with Fetch API and Async functions

  • remove all then() methods keeping the fetch and dispatch functions.
  • convert the returned arrow function into a regular function expression. Instead of the function keyword use async function to create an async function expression. Keep the dispatch function as an argument. The async keyword defines the function as an asynchronous function, which returns an AsyncFunction object and and uses an implicit Promise object to return its result.
  • create a new variable (let response in the code example) to store the asynchronous response returned by the fetch() method request. Asynchronous operations require anteposing the keyword await. As the documentation explains, the await keyword creates an await expression that pauses the execution of the asynchronous function (fetch) and waits for the passed Promise’s resolution. Upon reception, it resumes the async function's execution and returns the resolved value.
  • create a new variable (let responseJSON in the code example) to store the the result of parsing the body text as JSON with the json() method. This method returns a promise, so use the await keyword to create an await expression.
  • create a new sync function statement (dispatchLogin() in the code example) inside your async function taking as argument the async JSON response. The JSON response will be use to call the dispatch function.
  • finally, call and return the dispatchLogin() function. Pass the responseJSON variable as an argument. This variable depends on the async request from fetch(). As the documentation explains, there is no await statement on the return statement, because the return value of an async function is implicitly wrapped in Promise.resolve. As an alternative to the responseJSON variable, you could directly pass as an argument the await expression declared used in the responseJSON variable.

--

--

--

albertcarreras.github.io

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alberto Carreras

Alberto Carreras

albertcarreras.github.io

More from Medium

What is JWT. How to implement JWT based authentication in NodeJs?

How to implement JWT based authentication in NodeJs

Synchronous & Asynchronous Programming In JavaScript

NoSQL: Not Only SQL 🤔 || MongoDB