In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article is about how to request remote data in react. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
There are four ways to request remote data: 1, make a HTTP call directly in the React component and deal with the response; 2, create a folder and put the functions that are called by HTTP into it, centralize the request data and deal with the response; 3, customize Hook to request data; 4, use "react-query" or swr to request data.
The operating environment of this tutorial: Windows7 system, react17.0.1 version, Dell G3 computer.
Four methods of requesting remote data in React
React is a dedicated component library. Therefore, it has no advice on how to request remote data. If you want to request data through HTTP and send it to Web API, you can consider the following four ways.
Inline writing method
Centralized management
Custom Hook
React-query/swr
Note: in this article, I'll use fetch to make HTTP calls, but these patterns also apply to alternatives such as Axios. In addition, if you are using GraphQ L, consider other good options such as Apollo. This article assumes that you are calling traditional REST API.
Method 1: inline
This is the simplest and most direct choice. Make a HTTP call in the React component and process the response.
Fetch ("/ users") .then (response = > response.json ())
It looks simple. But this example ignores load status, error handling, declaration and setting related states, and so on. In the real world, the HTTP call looks more like this.
Import React, {useState, useEffect} from "react"; export default function InlineDemo () {const [users, setUsers] = useState ([]); const [loading, setLoading] = useState (true); const [error, setError] = useState (null); useEffect () = > {fetch (`${process.env.REACT_APP_API_BASE_URL} users`) .then (response = > {if (response.ok) return response.json (); throw response Then (json = > {setUsers (json);}) .catch (err = > {console.error (err); setError (err);}) .finally (() = > {setLoading (false);});}, []); if (loading) return "Loading..."; if (error) return "Oops!"; return users [0] .username;}
For a simple application, it only takes a few requests to work. But the above status statement and useEffect are templates. If I have to make many HTTP calls, I don't want to repeat and maintain about 20 lines of code for each call. Inline calls make your code ugly.
Take a look at some of the problems we are trying to solve:
Declare load status
Declare error status
Print errors to the console
Check whether the response is returned by 200 response.ok
If the response is normal, convert the response to json and return promise
If the response is incorrect, throw an error
Hide the load status in finally to ensure that Loading is hidden even if an error occurs
Declare an empty array of dependencies so that useEffect runs only once
This is just a simple example that ignores many other related issues.
Method 2: centralized management of folders
What if we handle all the HTTP calls in one folder? Using this approach, we create a folder called services and put in all the functions that make HTTP calls. Service is the most popular term, and I've discussed many good alternative names, such as client or api, below.
The point is that all HTTP calls are handled by pure JavaScript functions and stored in a folder. This is a centralized getUsers function:
Export function getUsers () {return fetch (`${process.env.REACT_APP_API_BASE_URL} users`) .then (response = > response.json ());}
The following is the call to the getUsers function:
Import React, {useState, useEffect} from "react"; import {getUsers} from ". / services/userService"; export default function CentralDemo () {const [users, setUsers] = useState ([]); const [loading, setLoading] = useState (true); const [error, setError] = useState (null); useEffect () = > {getUsers () .then (json = > {setUsers (json); setLoading (false)) ) .catch (err = > {console.error (err); setError (err);});}, []); if (loading) return "Loading..."; if (error) return "Oops!"; return users [0] .username;}
However, this does not simplify the request call. The main benefit is that it can force HTTP calls to be handled consistently. The idea is that when related functions are processed together, it is easier to deal with them consistently. If the userService folder is full of functions that make HTTP calls, I can easily make sure they do so consistently. In addition, if the calls are reused, they can easily be called from this centralized location.
However, we can do better.
Method 3: customize Hook
With the magic of React Hooks, we can finally focus on repetitive logic. So how do we create a custom useFetch hook to simplify our HTTP calls?
Import {useState, useEffect, useRef} from "react"; / / This custom hook centralizes and streamlines handling of HTTP callsexport default function useFetch (url, init) {const [data, setData] = useState (null); const [loading, setLoading] = useState (true); const [error, setError] = useState (null); const prevInit = useRef (); const prevUrl = useRef (); useEffect () = > {/ / Only refetch if url or init params change. If (prevUrl.current = url & & prevInit.current = = init) return; prevUrl.current = url; prevInit.current = init; fetch (process.env.REACT_APP_API_BASE_URL + url, init) .then (response = > {if (response.ok) return response.json (); setError (response);}) .then data = > setData (data) .catch (err = > {console.error (err)) SetError (err);}) .finally (() = > setLoading (false));}, [init, url]); return {data, loading, error};}
Yours may look different, but I find this basic usage very useful. This Hook greatly simplifies all calls. See how much code is required to use this Hook:
Import React from "react"; import useFetch from ". / useFetch"; export default function HookDemo () {const {data, loading, error} = useFetch ("users"); if (loading) return "Loading..."; if (error) return "Oops!"; return data [0] .username;}
For many applications, you only need one such custom Hook. But this Hook is already very complex, and it eliminates many problems.
But there are a lot of things we haven't considered: caching? If the connection of the client is unreliable, how to get it again? Do you want to retrieve new data when the user adjusts the tag? How to eliminate duplicate queries?
You can constantly refine this custom Hook to do all of these things. However, you should only need method 4:
Mode 4:react-query/swr
With react-query or swr, you can handle caching, retry, repeat queries, and so on for us. I don't have to maintain my own custom Hook. And each HTTP call requires very little code:
Import React from "react"; import {getUsers} from ". / services/userService"; import {useQuery} from "react-query"; export default function ReactQueryDemo () {const {data, isLoading, error} = useQuery ("users", getUsers); if (isLoading) return "Loading..."; if (error) return "Oops!"; return data [0] .username;} Thank you for reading! This is the end of the article on "how to request remote data in react". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.