Using an async Function | Lecture 142 | React.JS 🔥

The Coding Classroom
8 Dec 202305:41

Summary

TLDRIn this video, the presenter demonstrates how to convert a synchronous promise handling to an asynchronous function within a React effect. They explain the importance of avoiding race conditions and the limitations of effect callbacks. The tutorial shows how to create a new async function, 'fetchMovies', to handle API calls and update state, while also addressing the issue of stale state by using the latest data. The video also touches on React's strict mode and its impact on effect calls during development, ensuring that potential issues are caught before production.

Takeaways

  • 🔄 Converting a function to async allows for cleaner handling of Promises using async/await syntax.
  • 🚨 ESLint warns against using async functions directly in effect callbacks due to React's requirement for them to be synchronous.
  • 🎯 To work with async functions in React effects, encapsulate the async logic in a separate function that is called within the effect.
  • ✅ The await keyword is used to wait for the Promise to resolve within the async function.
  • 📦 Data fetched from an API is typically converted to JSON, which is an asynchronous operation.
  • 🔧 State updates in React are asynchronous, meaning the state may not be immediately updated after a setState call.
  • 🔍 Logging state to the console right after a state update might show stale data due to the asynchronous nature of state changes.
  • 🔁 React's strict mode in development doubles the number of effect calls to help identify potential issues with effects.
  • 🛠 Removing strict mode can demonstrate the actual number of HTTP requests made, but it's recommended to keep it for safety in development.
  • 📈 Adding a loading state can improve the user experience by indicating when data fetching is in progress.

Q & A

  • What is the purpose of converting a promise handling to an async function?

    -Converting promise handling to an async function makes the code easier and nicer to manage, especially when dealing with complex asynchronous operations.

  • Why can't we directly use an async function in the effect callback of `useEffect`?

    -Effect callbacks in `useEffect` must be synchronous to prevent race conditions. Async functions return promises, which are not allowed in this context.

  • How does the speaker suggest handling the limitation of not using async functions directly in `useEffect`?

    -The speaker suggests creating a new function outside of the `useEffect` and then placing the async function within that new function to avoid the ESLint warning.

  • What is the role of the `fetchMovies` function in the script?

    -The `fetchMovies` function is an async function that is used to fetch data from an API and is called within the effect to handle the data fetching logic.

  • Why does the speaker mention that setting state is asynchronous?

    -Setting state in React is asynchronous to ensure that the state updates do not cause race conditions. This means that the state is not updated immediately after the instruction to set it.

  • What is the issue with logging the `movies` state before it is updated?

    -Logging the `movies` state before it is updated results in an empty array because the state update is asynchronous and has not yet been applied when the log statement is executed.

  • How does the speaker address the issue of logging the updated `movies` state?

    -The speaker suggests using the variable `data.Search` instead of `movies` in the log statement to correctly display the fetched data.

  • What is the purpose of React's strict mode in the context of effects?

    -React's strict mode, when activated, calls effects twice in development to help identify potential issues with the effects. This does not occur in production to ensure performance.

  • Why does the speaker recommend keeping strict mode enabled in the code?

    -Keeping strict mode enabled is recommended because it provides additional safety checks during development, helping to identify and fix potential problems with the effects before the application goes into production.

  • What is the next step the speaker plans to cover in the video series?

    -The next step the speaker plans to cover is adding a loading state to the data fetching process to improve the user experience and provide feedback while data is being fetched.

Outlines

00:00

🔄 Converting to Async Functions

The script discusses the process of converting a function that handles promises into an asynchronous function for better code management. It highlights the use of async/await for handling promises and the importance of understanding the concept before proceeding. The script also addresses the ESLint warning about effect callbacks being synchronous and the solution of creating a new function to place the async function within. The example given involves fetching movies from an API, handling the response, and setting state. It also touches on the issue of stale state due to the asynchronous nature of state updates and the behavior of React's strict mode, which doubles the effect calls in development for debugging purposes.

05:03

🔧 Debugging and State Management

This paragraph focuses on debugging the code to understand why there are two outputs and HTTP requests when fetching data. It explains that React's strict mode in development can cause effects to run twice, which is not the case in production. The script then demonstrates how removing strict mode affects the output and HTTP requests, confirming that the effect is called only once. Finally, it suggests adding a loading state to the data fetching process to improve the user experience.

Mindmap

Keywords

💡async function

An async function is a JavaScript function that can use the `await` expression. It's used to simplify the handling of Promises, making asynchronous code easier to read and write. In the video, the speaker converts a function to an async function to handle a promise more elegantly, which is a common practice in modern JavaScript development, especially when dealing with asynchronous operations like fetching data from an API.

💡await

The `await` keyword is used with a Promise to wait for its resolution. It can only be used inside an async function and it pauses the execution of the async function until the Promise is resolved or rejected. In the video, the speaker uses `await` to wait for the response from the API and then processes the data, which is a fundamental concept in asynchronous programming.

💡ESLint

ESLint is a static code analysis tool for identifying and reporting on patterns in JavaScript. It helps developers find and fix problems in their code, adhering to certain coding standards. In the video, ESLint warns against using async functions in effect callbacks, which are meant to be synchronous to prevent race conditions.

💡race conditions

A race condition occurs when two or more processes access shared data and try to change it at the same time. This can lead to unpredictable results. In the context of the video, the speaker mentions that effect functions in React should be synchronous to avoid such issues, ensuring that state updates don't conflict with each other.

💡React

React is a JavaScript library for building user interfaces, particularly useful for creating single-page applications. It allows developers to create reusable UI components and manage their state efficiently. The video discusses the use of React's `useEffect` hook and its interaction with async functions and Promises.

💡useEffect

The `useEffect` hook in React is used to perform side effects in function components. It's similar to the `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` lifecycle methods combined. In the video, the speaker uses `useEffect` to handle data fetching and state updates.

💡state

In React, state is an object that represents the data that can change over time in a component. It's used to manage the internal state of a component and trigger re-renders when the state changes. The video discusses the asynchronous nature of state updates and how they relate to the timing of effects.

💡Promise

A Promise in JavaScript is an object that may produce a single value in the future. It represents a proxy for a value not necessarily known when the promise is created. Promises are used to handle asynchronous operations, like fetching data from an API. In the video, the speaker discusses the conversion of Promises to async functions for better code readability.

💡strict mode

React's strict mode is a way to enable additional checks and warnings for a component and its children. It helps developers catch potential problems in development, which are not present in production builds. In the video, the speaker explains that React 18's strict mode causes effects to run twice in development, which is a feature to help identify issues with effects.

💡loading state

A loading state is a UI pattern used to inform users that an operation is in progress, such as fetching data. It's a way to manage user expectations and provide feedback during asynchronous operations. In the video, the speaker plans to add a loading state to the data fetching process to improve the user experience.

Highlights

Converting effect to an async function for easier promise handling.

Using async/await for cleaner code when dealing with promises.

ESLint warning about effect callbacks being synchronous to prevent race conditions.

Effect functions in useEffect cannot return a promise.

Creating a new function to wrap the async function for use within useEffect.

Adapting the function to use the await keyword for asynchronous operations.

Setting state is asynchronous and does not happen immediately.

React's strict mode causing effects to run twice in development for error detection.

Removing strict mode results in only one HTTP request, indicating the effect was called once.

React's strict mode is a safety feature to identify issues with effects.

The initial state is an empty array, leading to stale state issues.

Using data.Search to access the correct state value after state has been set.

Logging the received movies to the console to demonstrate state updates.

React 18's strict mode behavior differs between development and production.

The video aims to make data fetching more complete with a loading state.

The async function fetchMovies is defined and called within the effect.

The use of the yellow underline in the code editor indicates a problem with the function call.

The video demonstrates the concept of stale state by showing an empty array in the console.

The video explains the difference between development and production behavior in React's strict mode.

Transcripts

play00:01

‫Let's now convert our effect to an async function

play00:04

‫instead of the basic promise handling

play00:07

‫that we're doing right now.

play00:10

‫So, many times when we need a lot of code

play00:13

‫to handle a promise,

play00:14

‫it's a lot easier and nicer to just have an async function.

play00:19

‫And here, I will just assume

play00:20

‫that you already know what async await is.

play00:25

‫So we might think that all we need to do

play00:28

‫in order to use an async function

play00:30

‫is to place the async keyword here,

play00:33

‫and then use await inside of it.

play00:37

‫However, we immediately get this warning from ESLint

play00:41

‫which tells us that effect callbacks

play00:43

‫are synchronous to prevent race conditions.

play00:47

‫So basically the effect function

play00:49

‫that we place into use effect cannot return a promise,

play00:54

‫which is what an async function does.

play00:58

‫So instead of doing it directly like this,

play01:01

‫we just create a new function.

play01:08

‫And then we place the async function in there.

play01:12

‫So let's call this one fetchMovies.

play01:17

‫And then let's of course adapt this function here,

play01:21

‫to using the await keyword.

play01:25

‫So const res equals await,

play01:29

‫and again, I'm assuming that you already know

play01:33

‫how all of this works.

play01:35

‫So that converting to promises to an async function

play01:38

‫is nothing new for you at this point.

play01:42

‫So data will be the result

play01:44

‫of converting the response to JSON,

play01:48

‫which is again, an asynchronous operation.

play01:53

‫And then, finally, we can set the movies to data.Search.

play01:59

‫So just what we had here.

play02:04

‫All right.

play02:05

‫But now of course nothing is happening,

play02:07

‫because nowhere we are calling this function.

play02:11

‫So that's also why this gets this yellow underline here.

play02:14

‫So our effect is now this function right here.

play02:19

‫But this function, all it's doing right now,

play02:21

‫is to define yet another function.

play02:24

‫So this async fetchMovies.

play02:26

‫And so then at the end, we just call it,

play02:30

‫and then it is back to working.

play02:32

‫Now here, I just want to extract this here

play02:35

‫for now into another variable,

play02:37

‫which I'm going to call query.

play02:42

‫And this is just temporary here.

play02:47

‫Now, okay.

play02:48

‫And now what I also want to do is to log our movies here.

play02:53

‫So the movies that we received from the API to the console,

play02:56

‫just so I can show you something.

play02:59

‫Let's first reload to get rid of the arrows there.

play03:03

‫And now what I want to do here, again,

play03:06

‫is to log our movies to the console.

play03:09

‫So, do you think that I can just do this?

play03:12

‫So you think that this is going to work?

play03:15

‫Well, let's see.

play03:17

‫And let's reload to actually see the truer result,

play03:20

‫which is an empty array.

play03:23

‫So why is this happening?

play03:25

‫Well, hopefully you learned in the previous section

play03:28

‫that setting state is asynchronous.

play03:31

‫So in other words, after the state

play03:34

‫has been set here in this line of code,

play03:37

‫or actually after we instructed React to set the state,

play03:41

‫that doesn't mean that this happens immediately.

play03:44

‫So instead, it will happen

play03:46

‫after this function here has been called.

play03:48

‫And so right here in this line of code, we have stale state

play03:53

‫which basically means that we still have the old value

play03:56

‫as the state was before.

play03:58

‫And in this case, before, it was just the empty array.

play04:01

‫So our initial state.

play04:04

‫So here we can basically then use data.Search again.

play04:09

‫And so, as we reload now, then we get here the output.

play04:14

‫Now what I wanted to talk about

play04:17

‫is why we always have these two outputs.

play04:19

‫So, basically why we have these two requests here happening.

play04:23

‫Well, the reason for that is React's strict mode.

play04:27

‫So when strict mode is activated in React 18,

play04:31

‫our effects will not run only once, but actually twice.

play04:36

‫So React will call our effects twice

play04:39

‫but only in development.

play04:41

‫So when our application is in production,

play04:43

‫this will no longer be happening.

play04:45

‫And so this is just so that React can identify

play04:48

‫if there are any problems with our effects.

play04:52

‫So if we come here quickly just to index.JS

play04:56

‫and if we remove the strict mode from here,

play05:02

‫well then we have this problem.

play05:05

‫Let's actually remove the code.

play05:07

‫Let's save and let's reload.

play05:09

‫And then you see that we only get one output here,

play05:13

‫which means that there was only one HTTP request.

play05:18

‫So the effect was only called once indeed.

play05:22

‫But let's put it back

play05:23

‫because this is somehow a bit safer.

play05:28

‫Now, okay, and that's it for this video.

play05:31

‫Next up, let's make this data fetching here

play05:34

‫a bit more complete with a loading state.

Rate This

5.0 / 5 (0 votes)

Related Tags
ReactAsyncAwaitPromisesState ManagementESLintRace ConditionsAPI CallsDebuggingStrict ModeWeb Development