Javascript async/await in React Components

Again some notes from my recent React and Javascript/TypeScript learnings. I knew already how to use Promises by building method chains with .then()
or .catch()
to chain the asynchronous actions together. But as I am a fan of C#’s async
and await
and read that JS/TS does support them too, I liked to figure how to use them in my React apps so the code will get even cleaner as with the method chains.
Scenario
When my React UI need data they have to request them from a REST-Server (API). Best practice here is to do this work asynchronous so the UI-Thread stays responsive.
When speaking of React UI I mean a React.Component using its standard methods that like componentDidMount()
. This method is where one should load the server-data with regards to the React doc’s. This method is normally not marked async
and therefore one can not use await
. I guess this is why many React developers don’t use await
but method chains.
Solution
How can I utilise await
to simplify my asynchronous code in React apps?
First I implemented an async service-method which will be responsible to fetch data from the server (for example by using the fetch()
API which is based on Promises).
The following code is my in-memory test-service which returns fixed values instead calling a real server. Hint: I used the Promise.resolve()
function to return the fixed value right away.
async getEntities(): Promise { return Promise.resolve(entities); }
Note the async
keyword here and that I return a Promise. Side-note for C# developers: Javascript Promise
is exactly that Task
is in C#.
Then I’ve changed my React Component’s componentDidMount()
mount method to an async method by also using the async
keyword:
export class ContactList extends React.Component { ... async componentDidMount() { const entities = await apiManager().contactService.getEntities(); this.setState({ entities }); } ... }
Please not that this way I can use await
to await the result of my async function getEntities()
.
React seems to call this componentDidMount()
even if it is async now.
Cool – eyy?
Categories