Asincronicitate in React
What is async and why is it important in React?
Asynchronicity is the ability of an application to run multiple computations in parallel without being blocked by processing that takes longer or requires waiting. In React, asynchronicity is important because applications are largely built around events and data that change in real time. Therefore, it is important to be able to run asynchronous processes while the application remains responsive.
For example, when we make a request to a server to get information to display on a page, it may take some time. During this time, the application should not crash or stop working. Instead, React can use asynchronicity to run the process in the background without blocking the rest of the application.
Additionally, asynchronicity is important in React to handle real-time events and animations. For example, when the user clicks a button to perform an action, the application must respond quickly to give the user a real-time response. By using asynchronicity, the application can run processing in the background without blocking the rest of the application and without slowing down the response.
In conclusion, asynchronicity is important to ensure good performance and a pleasant user experience. By running asynchronous processes, the application can remain responsive and handle events and data in real time.
Using asynchronous APIs in React
In React, we can use asynchronous APIs to get and process data from external servers. This can be done using functions such as fetch, axios or XMLHttpRequest to make HTTP requests to a server. Asynchronous APIs are essential in modern application development because they allow data to be fetched in real-time without the need to load an entire page.
To use asynchronous APIs in React.js, we need to create a component that uses such a function. A common approach is to use fetch to make a GET request to the server to get the data. When the data is received, we can use the setState method to update the state of the component with the new data.
import React, { useEffect, useState } from 'react';
type GetDataState = {
data: { id: number, title: string }[] | null,
isLoading: boolean,
error: { message: string } | null
}
export const TaskList = () => {
const [state, setState] = useState<GetDataState>({
data: null, // we set the initial state where the data is not yet available
isLoading: false, // we also want to know when the data is loading
error: null // if we have errors we can do something about them, not ignore them
});
useEffect(() => { // use useEffect to perform additional actions when initializing/updating the component
if (state.data !== null || state.isLoading) { // if the data is loaded or about to be loaded, we do nothing
return;
}
setState({ isLoading: true, data: null, error: null }); // we set here that the data is loaded
fetch('https://jsonplaceholder.typicode.com/todos') // perform the asynchronous operation
.then(response => response.json()) // when the data is available we deserialize it
.then(data => setState({ data, isLoading: false, error: null })) // with the deserialized object we set the new state
.catch(error => setState({ error, isLoading: false, data: null })); // if an error occurred we set it to state
}, [state]); // the list as a parameter is used to call the useEffect function when changing the objects in the list
// depending on the current state we display the component accordingly
if (state.error) {
return <p>{state.error.message}</p>;
}
if (state.isLoading) {
return <p>Loading...</p>;
}
return <div>
<h1>Task list:</h1>
<ul>
{state.data?.map(task => <li key={task.id}>{task.title}</li>)}
</ul>
</div>
}
In this example, we used fetch to get a list of tasks from the JSONPlaceholder server. I updated the state of the component with the data obtained from the server using the setState method. If we encounter an error during the data fetching process, we display an error message. Finally, I displayed the list of tasks via a mapping of the received data to a list. Here I also used the hook function useEffect which automatically calls the function given as a parameter when initializing or updating the component when the list of given dependencies has changed, in this case the state exposed through useState.
In conclusion, using asynchronous APIs in React is essential to get data from external servers and update components in real-time without having to load an entire page.
This example is only used as a demonstration of using asynchronous functions in React and how to work with them in general. However, in practice, various packages and tools are used to facilitate and abstract working with asynchronous requests. For this reason, follow our documentation for using the ReactQuery library and the OpenAPI Generator utility.