React Hooks – How to Fetch Data from API

Let's Learn React Hooks and Context API by Building a Recipe ...

The React team invented React Hooks to introduce state management and side-effects in the function components. The hooks enable writing React apps with just the function components. The hooks of React is a feature proposal that’s developed to have access to all the features used in classes from functional components.

In React web development, the motivation proposals are the following:

  • Reduce components complexity
  • Stateful components logic reusability
  • The entry point for particular optimizations

The idea is giving power to functional components in the React realm.

With years of experience,  company like eTatvaSoft could state that the React framework is the best when it comes to developing fast and large web apps with JavaScript. Moreover, it enables the creation of interactive UIs, updates components in a smooth manner, develops new features without having to rewrite code, as well as dealing with SEO more efficiently, all thanks to the server-side rendering.

Using React Hooks

Embracing the use of React hooks would lower the number of concepts required to juggle when writing apps in the framework. The hooks allow the utilization of functions at all times, rather than switching from function to function, classes, higher-order components, and render props constantly.

Fetching API data with React Hooks

C:\Users\Llesol-Family\Pictures\react.png

Both functionalities of state and the state update come from the useState, a state hook that’s responsible for managing local data state that we would be fetching for the Application component. The initial phase is an empty hits list in an object representing the data. Nobody will set any state for the data rate.

We’ll be using Axios for fetching data. Nonetheless, it depends on you if you prefer to use another fetching library or even a native fetch browser API. If you have no Axios installed yet, you can install it with the command line, npm install Axios. You could afterward implement the effect hook for data fetching:

C:\Users\Llesol-Family\Pictures\react1.png

The useEfect, effect hook is used to fetch data from the API using Axios and set the data in the local state of the component with the update function of state hook. However, running an app could make you stumble into a nasty loop. Effect hooks run when the component mounts, as well as when a component updates.

Because we would be setting state after every fetched data, the effect and component updates would again run. It will fetch data repeatedly, a bud that should be avoided. When the component mounts, that’s the time we would only fetch data. We therefore could provide an empty range as a second argument to the hook effect. This is done to prevent being activated on the component updates. It should only be activated only for mounting the component.

C:\Users\Llesol-Family\Pictures\react2.png

The second argument could be used in defining all variables where the hook depends. If there is a change to one of the variables, the hook will run again. If the variables array is empty, the hook will not run when you update the component since it need not watch any variables.

There is the last catch however. To get data from a third-party API in code, we would be using async/await. Based on the documentation, each annotated function with async will return an implicit reply. An effect hook however should not return anything, or what’s called as a clean-up function. Thus, it’s not allowed to use async directly in the useEffect function. We’ll do a workaround for it using the async functionality within the effect.

C:\Users\Llesol-Family\Pictures\react3.png

C:\Users\Llesol-Family\Pictures\react4.png

In a nutshell, that’s data fetching using React hooks. However, if you’re interested in handling error, how to load indicators, how to implement a reusable data fetching hook and how to trigger fetching data from a form, you should continue reading.

Trigger a Hook Manually/Programmatically/

Let’s consider using an input field to tell the API the topic that we’re interested in. Be default query, Redux is used. Nonetheless, what about ‘React’ topics? What about topics on ‘React’? We will implement an input element to allow someone to fetch other stories, thus introduce a new input element state.

C:\Users\Llesol-Family\Pictures\react5.png

C:\Users\Llesol-Family\Pictures\react6.png

Both of the states at present are not dependent on each other. But we have to couple them to fetch only the specified input field query articles. The component of the following field must get all articles by the query term once mounted.

C:\Users\Llesol-Family\Pictures\react7.png

A piece is missing though. No effect will be triggered when you try typing something on the input field. This is because you have provided an empty array as a second effect argument. The effect will not depend on variables; thus it’s only triggered when a component mounts.

Nonetheless, the effect now should depend on the query. The data requests should fire again once a query would change.

C:\Users\Llesol-Family\Pictures\react8.png

Once you change the value in the input field, data re-fetching should work. This however opens another issue, and that is: on each character that you type on the input field, the effect is triggered and would execute and get the data request. Provide a button that would manually trigger the request and so the hook.

C:\Users\Llesol-Family\Pictures\react9.png

C:\Users\Llesol-Family\Pictures\react10.png

Consider making the effect dependent on the search state, rather than the fluctuant query state that with every major stroke in the input field will alter. The moment a user would click on a button, it will set a new search sate and sort of trigger the effect hook in a manual manner.

C:\Users\Llesol-Family\Pictures\react11.png

The same as the state of query state, the initial state is also set because the component fetches the data on mount as well, in which the result must reflect the value of the input field. Nonetheless, having the same search state and query could be confusing. We must try setting the actual URL as a state, rather than the search state.

C:\Users\Llesol-Family\Pictures\react12.png

C:\Users\Llesol-Family\Pictures\react13.png

That would be it for the implicit programmatic fetching of data with effect hook. You could make a decision on what state the effect would depend on. When you set the sate on a click or in another side-effect, the effect will again run. In this way, if there is a change to the URL state, the effect will again run to fetch API stories.

Conclusion

You get to learn how React Hooks for state and effects can be used to fetch API data.

0