You’re probably used to fetching data in React using axios or fetch. The usual method of handling data fetching is to:
There will always be delays when handling requests over the network. That’s just part of the deal when it comes to making a request and waiting for a response. That’s why we often make use of a loading spinner to show the user that the expected response is loading. See the Pen All these can be done using a library called React Async. React Async is a promised-based library that makes it possible for you to fetch data in your React application. Let’s look at various examples using components, hooks and helpers to see how we can implement loading states when making requests. For this tutorial, we will be making use of Create React App. You can create a project by running:
When that is done, run the command to install React Async in your project, using yarn or npm:
Example 1: Loaders in componentsThe library allows us to make use of
First, we created a function called The props are:
As you can see from the example, we return something to be displayed to the user dependent on the prop. Example 2: Loaders in hooksIf you are a fan of hooks (as you should), there is a hook option available when working with React Async. Here’s how that looks:
This looks similar to the component example, but in this scenario, we’re making use of Example 3: Loaders in helpersHelper components come in handy in making our code clear and readable. These helpers can be used when working with an
This looks similar to when we were making use of props. With that done, you could break the different section of the app into tiny components. ConclusionIf you have been growing weary of going the route I mentioned in the opening section of this tutorial, you can start making of React Async in that project you are working on. The source code used in this tutorial can be found in their different branches on GitHub. The post Fetching Data in React using React Async appeared first on CSS-Tricks. from CSS-Tricks https://css-tricks.com/fetching-data-in-react-using-react-async/ Fetching Data in React using React Async is available on www.instant-web-site-tools from https://www.instant-web-site-tools.com/2019/07/31/fetching-data-in-react-using-react-async/
0 Comments
Leave a Reply. |