In a typical software architect that seperates backend (Nodejs) and frontend (React), the frontend is quite ‘light weighted’ in terms of operations regarding data (Also grâce à the tools like react-redux, the frontend development is easier). That means we normally do not need to cope with scenarios that needs to write complex Nodejs code on the frontend side as it is just a viewer. However, due to certain features of React, there are some scenarios that we need to pay attention to. In this article, I summarise two typical scenarios that using ‘async’ within React in a recent project.
Calling Async Method in ‘useEffect’
There are some cases that we need to call async method in useEffct. Can we do things like below:
1 | useEffect(async () => { |
No, we cannot. Why? Because the async axios call returns promise and the useEffect does not expect callback function to return promise. The useEffect waits for the return of nothing or a function.
Then what we should do? There are two methods
- Define an async function inside useEffect
1 | useEffect(() => { |
- Define an async function outside useEffect
1 | const getData = useCallBack (async () => { |
Use Async in ‘setInterval’
1 | setInterval(async () => { |
Can we do things like above in setInterval? It is questionable, as the async call may cost more than the time set in setInterval method. So what is the better option? Use Promise with setTimeout, like below:
1 | function delay(ms) { |
Reference: https://stackoverflow.com/questions/51830200/how-to-await-inside-setinterval-in-js
The above are the two scenarios that I met in my project, when I look back as a new full-stack engineer (I was heavily involved in backend dev, not frontend):)