#formdata react
Explore tagged Tumblr posts
Text
How to Send Form Data Using Axios Post Request in React

Many developers use React, a leading programming language for app development. Industry leaders prefer React for cross-platform application development. A proper understanding of React and the library is essential to work well for the project. If you want to handle react project properly, you can hire react developer and finish the task.
As a React developer, sending form data to a server in react with the Axios. Processing axios is an important javascript library. It is the best way to make HTTP requests from a browser or nodejs. Individuals must understand how to use the Axios to make a post request and send form data.
About Axios:
Axios acts as an HTTP client for JavaScript that works in browser and node.js. It is an easy-to-use and lightweight library that delivers the perfect interface for HTTP requests. Axios can build on top of XMLHttpRequest API and fetch API.Â
On the other hand, it supports promise API and intercepts responses. Axios is responsible for transforming requests, canceling requests, and response data. It is excellent for changing JSON data and provides client-side support to safeguard from the XSRF. It supports browsers like Safari, Mozilla Firefox, Google Chrome, Edge, and IE.
Form data:
Form data is the encoding type that transfers to the server for processing. Other encoding types can be utilized for non-file transfer like plain, text, application/x-www-form-urlencoded, and a lot more. React developer helps you in sending form data in react projects with Axios.
If form-data lets files to include in form data, plain or text propel data as plain text without encoding. It is applicable for debugging and not for production. Application/x-www-form-urlencoded instructs data as a query string. Encoding type can be included in HTML with enctype attribute.Â
Send form data in the Axios request:
Sending form data in the React app to the server is an important task among many developers. Axios is an important library for making HTTP requests quickly in React. You can understand the important process of sending form data in the react project using Axios.Â
While using Axios, developers easily make post requests and set the data they wish to send as a request body. If you carry out this process, you can utilize the Axios.post() method that acquires two arguments. It obtains arguments like server URL and data you need to send.Â
FormData object joins two fields with matching values. It makes HTTP requests to specific URLs with a FormData object. It uses them as a request body and sets the content-type header to multipart or form data.
Once the request is successful, the response can log into the console. If the request is abortive, the error response can log to the console. Using Axios in the project requires installing Axios first. You can install it with the proper command.
Launch react project:
Whether you have a project already, you donât need to launch. If you donât have any projects on your device, you can create them first.Â
You can open a terminal and run the required command.Â
npx create-react-app axios-form
Once project creation is over, you can go to the project directory.
Install axios:
To use Axios for post requests in the React project, you must install it properly. You can use the following command to install the Axios.
npm install axios
After successfully installing the Axios, you can carry out sending the form data in a project with the Axios post request.
Create form component:
When it comes to the React project, you must make a new component for form. You can name it and save it with .js
// src/Form.js
import React, { useState } from âreactâ;
import axios from âaxiosâ;
function Form() {
const [formData, setFormData] = useState({
name: ââ,
email: ââ,
});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({ âŚformData, [name]: value });
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post(âYOUR_API_ENDPOINTâ, formData);
console.log(âForm data submitted successfully:â, response.data);
} catch (error) {
console.error(âError submitting form data:â, error);
}
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type=âtextâ
name=ânameâ
value={formData.name}
onChange={handleChange}
/>
</label>
<br />
<label>
Email:
<input
type=â emailâ
name=â emailâ
value={formData.email}
onChange={handleChange}
/>
</label>
<br />
<button type=âsubmitâ>Submit</button>
</form>
);
}
export default Form;
In this component, you can label the form with two input fields. You can utilize the useState hook to deal with form data. Axios is ideal for making the post request when the form submits successfully.
Import and apply form component:
After creating the form component, you need to import and apply the form component to the project.
// src/App.js
import React from âreactâ;
import Form from â./Formâ;
function App() {
return (
<div className=âAppâ>
<h1>React Form with Axios POST Request</h1>
<Form />
</div>
);
}
export default App;
Replace your_api_endpoint:
In the form component, you can replace your_api_endpoint with the actual endpoint. It is easy to send the form data in a project and complete them easily
Run React application:
After the above step is over, it is time to run the React application with the following command like
npm startÂ
React application is running and allows you to access it in the browser. You can fill out the form and click the submit button. You must view the form data that is sent to a specified API endpoint in the browser console. You can try the necessary steps for the form data sending in the project utilizing the Axios post request.Â
Conclusion:
Overall, the above details are useful to understand the process of sending the form data in react with Axios. With the help of a hire react expert, you can get the proper guidance and support to handle this process.Â
Experts assist you in integrating the form component with the server-side endpoint and dealing with the data effectively in a project. Axios makes a form data sending process in the react app development project. So, you can work with the skilled and knowledgeable react expert and obtain an ideal solution for challenges.Â
The React Company : Empowering Developers in React Technology.
Donât Hesitate to Get in Contact for More Info.
#hire react developer#React Development Services#React js development services#hire react js engineers#react js experts
0 notes
Text
React Form with Hooks: A Step-by-Step Tutorial
#react #reactjs #reacthook #reactform
I. Introduction React is a popular JavaScript library for building user interfaces, and forms are a crucial part of any web application. In this article, we will explore how to build React form using hooks, a powerful feature introduced in React 16.8. One of the key benefits of using hooks with forms is the ability to manage state in a more concise and efficient way. With hooks, we can easilyâŚ
View On WordPress
#Accessibility#best practices#common mistakes#Form Handling#form onsubmit react#Form Validation#form validation react#formdata react#Forms#hook form#Hooks#input validation#login page react#onsubmit react#Performance#React#react form#react form with hooks#react hook form
0 notes
Text
React Project(WODs)
This post will be about my final project, using React, of phase 2 at Flatiron school. I have had a lot of fun learning React and feel as though it almost better helped me understand JavaScript. At the same time though there were parts that I struggled with as well. Specifically, working with POST requests and forms, at first, challenged me for awhile.
Furthermore, for my project I created a web page that lists out different WODs, workout of the day, also includes alternative movements for the workout and even create your own WOD. Created the frontend using create-react-app to get the starting code. Then used a JSON server template provided by Flatiron for the backend. Within my frontend there is six components, App, Navbar, WodForm, Home, WodDescription, and Wod. App being the top component of all the others. App consists of all my fetch requests, GET and POST, state for JSON data, and renders out the Navbar, WodForm, Wod, and Home components, this is also all wrapped by router and gives all the routes to each of these.
My Navbar component uses NavLink to display links to both the Home page and Create WOD page. I gave them both an activeStyle so that when you are on that page the NavLink text turns red for that page. Next, is my Home component which takes the JSON data as a prop called wods. I created a variable to map through wods, which then renders the WodDescription component, and passes down each wod to it. My Home component is what displays WodDescription. WodDescription takes the wod and displays the workout, and how it will be scored. There is also a button that will take you to that specific WOD with alternative movements, if say, they are too difficult or heavy. I used the useHistory hook in order for it take you to that specific WOD that the button is on. Also, I had to incorporate string interpolation with wod.id in accordance with history.push.
My Wod component, as mentioned before, will display only the one WOD whose id matches with the url id. It will show the alternative movements, as well as, the workout and how it will be scored. I also had to pass wods down as a prop from the app, but I instead used find() method. Which returns the value of the first element in the provided array that matches the testing function. Within that method I used the useParams hook to compare its id, which is the URLâs id, and find the wod that has a matching id. I did also have to use parseInt() on the params because it was a string and I needed it to be an integer.
To complete this post, I will explain my WodForm component where I worked on one of the more challenging coding parts with React, for me. As I mentioned earlier all my fetch requests are done within my App component. So, I passed down my POST request to the WodForm component. This component is made up of a formData state variable, a handleChange function, handleSubmit function, and a form for submitting and POSTing this new WOD. The inputs use the handleChange function to get what the user types for both the workout and how it will be scored. Give these inputs a value of data.whicheverkeyitis. The form is given an onSubmit equal to the handleSubmit function. The handleSubmit function calls the POST request function and passes down the formData. This POST request then adds this workout to all the other already existing workouts set in the state. All in all, this is my project and I enjoyed watching the code work and do what I wanted it to in the browser, that is always a really good feeling!
0 notes
Text
Consuming REST APIs In React With Fetch And Axios
About The Author
Shedrack Akintayo is a software engineer from Lagos, Nigeria, who has a love for community building, open source and creating content and tech for the next ⌠More about Shedrack âŚ
If youâre a React developer whoâd like to learn how you can start consuming APIs in your React applications, then this article is for you. Shedrack Akintayo explains what a REST API is and how to build a simple application that consumes a REST API by using both Fetch API and Axios.
Consuming REST APIs in a React Application can be done in various ways, but in this tutorial, we will be discussing how we can consume REST APIs using two of the most popular methods known as Axios (a promise-based HTTP client) and Fetch API (a browser in-built web API). I will discuss and implement each of these methods in detail and shed light on some of the cool features each of them have to offer.
APIs are what we can use to supercharge our React applications with data. There are certain operations that canât be done on the client-side, so these operations are implemented on the server-side. We can then use the APIs to consume the data on the client-side.
APIs consist of a set of data, that is often in JSON format with specified endpoints. When we access data from an API, we want to access specific endpoints within that API framework. We can also say that an API is a contractual agreement between two services over the shape of request and response. The code is just a byproduct. It also contains the terms of this data exchange.
In React, there are various ways we can consume REST APIs in our applications, these ways include using the JavaScript inbuilt fetch() method and Axios which is a promise-based HTTP client for the browser and Node.js.
Note: A good knowledge of ReactJS, React Hooks, JavaScript and CSS will come in handy as you work your way throughout this tutorial.
Letâs get started with learning more about the REST API.
What Is A REST API
A REST API is an API that follows what is structured in accordance with the REST Structure for APIs. REST stands for âRepresentational State Transferâ. It consists of various rules that developers follow when creating APIs.
The Benefits Of REST APIs
Very easy to learn and understand;
It provides developers with the ability to organize complicated applications into simple resources;
It easy for external clients to build on your REST API without any complications;
It is very easy to scale;
A REST API is not language or platform-specific, but can be consumed with any language or run on any platform.
An Example Of A REST API Response
The way a REST API is structured depends on the product itâs been made for â but the rules of REST must be followed.
The sample response below is from the Github Open API. Weâll be using this API to build a React app later on in this tutorial.
{ "login": "hacktivist123", "id": 26572907, "node_id": "MDQ6VXNlcjI2NTcyOTA3", "avatar_url": "https://avatars3.githubusercontent.com/u/26572907?v=4", "gravatar_id": "", "url": "https://api.github.com/users/hacktivist123", "html_url": "https://github.com/hacktivist123", "followers_url": "https://api.github.com/users/hacktivist123/followers", "following_url": "https://api.github.com/users/hacktivist123/following{/other_user}", "gists_url": "https://api.github.com/users/hacktivist123/gists{/gist_id}", "starred_url": "https://api.github.com/users/hacktivist123/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/hacktivist123/subscriptions", "organizations_url": "https://api.github.com/users/hacktivist123/orgs", "repos_url": "https://api.github.com/users/hacktivist123/repos", "events_url": "https://api.github.com/users/hacktivist123/events{/privacy}", "received_events_url": "https://api.github.com/users/hacktivist123/received_events", "type": "User", "site_admin": false, "name": "Shedrack akintayo", "company": null, "blog": "https://sheddy.xyz", "location": "Lagos, Nigeria ", "email": null, "hireable": true, "bio": "â Software Engineer | | Developer AdvocateđĽ|| ⤠Everything JavaScript", "public_repos": 68, "public_gists": 1, "followers": 130, "following": 246, "created_at": "2017-03-21T12:55:48Z", "updated_at": "2020-05-11T13:02:57Z" }
The response above is from the Github REST API when I make a GET request to the following endpoint https://api.github.com/users/hacktivist123. It returns all the stored data about a user called hacktivist123. With this response, we can decide to render it whichever way we like in our React app.
Consuming APIs Using The Fetch API
The fetch() API is an inbuilt JavaScript method for getting resources from a server or an API endpoint. Itâs similar to XMLHttpRequest, but the fetch API provides a more powerful and flexible feature set.
It defines concepts such as CORS and the HTTP Origin header semantics, supplanting their separate definitions elsewhere.
The fetch() API method always takes in a compulsory argument, which is the path or URL to the resource you want to fetch. It returns a promise that points to the response from the request, whether the request is successful or not. You can also optionally pass in an init options object as the second argument.
Once a response has been fetched, there are several inbuilt methods available to define what the body content is and how it should be handled.
The Difference Between The Fetch API And jQuery Ajax
The Fetch API is different from jQuery Ajax in three main ways, which are:
The promise returned from a fetch() request will not reject when thereâs an HTTP error, no matter the nature of the response status. Instead, it will resolve the request normally, if the response status code is a 400 or 500 type code, itâll set the ok status. A request will only be rejected either because of network failure or if something is preventing the request from completing
fetch() will not allow the use of cross-site cookies i.e you cannot carry out a cross-site session using fetch()
fetch() will also not send cookies by default unless you set the credentials in the init option.
Parameters For The Fetch API
resource This is the path to the resource you want to fetch, this can either be a direct link to the resource path or a request object
init This is an object containing any custom setting or credentials youâll like to provide for your fetch() request. The following are a few of the possible options that can be contained in the init object:
method This is for specifying the HTTP request method e.g GET, POST, etc.
headers This is for specifying any headers you would like to add to your request, usually contained in an object or an object literal.
body This is for specifying a body that you want to add to your request: this can be a Blob, BufferSource, FormData, URLSearchParams, USVString, or ReadableStream object
mode This is for specifying the mode you want to use for the request, e.g., cors, no-cors, or same-origin.
credentials This for specifying the request credentials you want to use for the request, this option must be provided if you consider sending cookies automatically for the current domain.
Basic Syntax for Using the Fetch() API
A basic fetch request is really simple to write, take a look at the following code:
fetch('https://api.github.com/users/hacktivist123/repos') .then(response => response.json()) .then(data => console.log(data));
In the code above, we are fetching data from a URL that returns data as JSON and then printing it to the console. The simplest form of using fetch() often takes just one argument which is the path to the resource you want to fetch and then return a promise containing the response from the fetch request. This response is an object.
The response is just a regular HTTP response and not the actual JSON. In other to get the JSON body content from the response, weâd have to change the response to actual JSON using the json() method on the response.
Using Fetch API In React Apps
Using the Fetch API in React Apps is the normal way weâd use the Fetch API in javascript, there is no change in syntax, the only issue is deciding where to make the fetch request in our React app. Most fetch requests or any HTTP request of any sort is usually done in a React Component.
This request can either be made inside a Lifecycle Method if your component is a Class Component or inside a useEffect() React Hook if your component is a Functional Component.
For example, In the code below, we will make a fetch request inside a class component, which means weâll have to do it inside a lifecycle method. In this particular case, our fetch request will be made inside a componentDidMount lifecycle method because we want to make the request just after our React Component has mounted.
import React from 'react'; class myComponent extends React.Component { componentDidMount() { const apiUrl = 'https://api.github.com/users/hacktivist123/repos'; fetch(apiUrl) .then((response) => response.json()) .then((data) => console.log('This is your data', data)); } render() { return <h1>my Component has Mounted, Check the browser 'console' </h1>; } } export default myComponent;
In the code above, we are creating a very simple class component that makes a fetch request that logs the final data from the fetch request we have made to the API URL into the browser console after the React component has finished mounting.
The fetch() method takes in the path to the resource we want to fetch, which is assigned to a variable called apiUrl. After the fetch request has been completed it returns a promise that contains a response object. Then, we are extracting the JSON body content from the response using the json() method, finally we log the final data from the promise into the console.
Letâs Consume A REST API With Fetch Method
In this section, we will be building a simple react application that consumes an external API, we will be using the Fetch method to consume the API.
The simple application will display all the repositories and their description that belongs to a particular user. For this tutorial, Iâll be using my GitHub username, you can also use yours if you wish.
The first thing we need to do is to generate our React app by using create-react-app:
npx create-react-app myRepos
The command above will bootstrap a new React app for us. As soon as our new app has been created, all thatâs left to do is to run the following command and begin coding:
npm start
If our React is created properly we should see this in our browser window when we navigate to localhost:3000 after running the above command.
(Large preview)
In your src folder, create a new folder called component. This folder will hold all of our React components. In the new folder, create two files titled List.js and withListLoading.js. These two files will hold the components that will be needed in our app.
The List.js file will handle the display of our Repositories in the form of a list, and the withListLoading.js file will hold a higher-order component that will be displayed when the Fetch request we will be making is still ongoing.
In the List.js file we created inside the components folder, letâs paste in the following code:
import React from 'react'; const List = (props) => { const { repos } = props; if (repos.length === 0 || !repos) return <p>No repos, sorry</p>; return ( <ul> <h2 className='list-head'>Available Public Repositories</h2> {repos.map((repo) => { return ( <li key={repo.id} className='list'> <span className='repo-text'>{repo.name} </span> <span className='repo-description'>{repo.description}</span> </li> ); })} </ul> ); }; export default List;
The code above is a basic React list component that would display the data, in this case, the repositories name and their descriptions in a list.
Now, Let me explain the code bit by bit.
const { repos } = props;
We are initializing a prop for the component called repos.
if (repos.length === 0 || !repos) return <p>No repos, sorry</p>;
Here, all we are doing is making a conditional statement that will render a message when the length of the repos we get from the request we make is equal to zero.
return ( <ul> <h2 className='list-head'>Available Public Repositories</h2> {repos.map((repo) => { return ( <li key={repo.id} className='list'> <span className='repo-text'>{repo.name} </span> <span className='repo-description'>{repo.description}</span> </li> ); })} </ul> );
Here, we are mapping through each of the repositories that will be provided by the API request we make and extracting each of the repositories names and their descriptions then we are displaying each of them in a list.
export default List;
Here we are exporting our List component so that we can use it somewhere else.
In the withListLoading.js file we created inside the components folder, letâs paste in the following code:
import React from 'react'; function WithListLoading(Component) { return function WihLoadingComponent({ isLoading, ...props }) { if (!isLoading) return <Component {...props} />; return ( <p style=> Hold on, fetching data may take some time :) </p> ); }; } export default WithListLoading;
The code above is a higher-order React component that takes in another component and then returns some logic. In our case, our higher component will wait to check if the current isLoading state of the component it takes is true or false. If the current isLoading state is true, it will display a message Hold on, fetching data may take some time . Immediately the isLoading state changes to false itâll render the component it took in. In our case, itâll render the List component.
In your *App.js file inside the src folder, letâs paste in the following code:
import React, { useEffect, useState } from 'react'; import './App.css'; import List from './components/List'; import withListLoading from './components/withListLoading'; function App() { const ListLoading = withListLoading(List); const [appState, setAppState] = useState({ loading: false, repos: null, }); useEffect(() => { setAppState({ loading: true }); const user = `https://api.github.com/users/hacktivist123/repos`; fetch(user) .then((res) => res.json()) .then((repos) => { setAppState({ loading: false, repos: repos }); }); }, [setAppState]); return ( <div className='App'> <div className='container'> <h1>My Repositories</h1> </div> <div className='repo-container'> <ListLoading isLoading={appState.loading} repos={appState.repos} /> </div> <footer> <div className='footer'> Built{' '} <span role='img' aria-label='love'> đ </span>{' '} with by Shedrack Akintayo </div> </footer> </div> ); } export default App;
Our App.js is a functional component that makes use of React Hooks for handling state and also side effects. If youâre not familiar with React Hooks, read my Getting Started with React Hooks Guide.
Let me explain the code above bit by bit.
import React, { useEffect, useState } from 'react'; import './App.css'; import List from './components/List'; import withListLoading from './components/withListLoading';
Here, we are importing all the external files we need and also the components we created in our components folder. We are also importing the React Hooks we need from React.
const ListLoading = withListLoading(List); const [appState, setAppState] = useState({ loading: false, repos: null, });
Here, we are creating a new component called ListLoading and assigning our withListLoading higher-order component wrapped around our list component. We are then creating our state values loading and repos using the useState() React Hook.
useEffect(() => { setAppState({ loading: true }); const user = `https://api.github.com/users/hacktivist123/repos`; fetch(user) .then((res) => res.json()) .then((repos) => { setAppState({ loading: false, repos: repos }); }); }, [setAppState]);
Here, we are initializing a useEffect() React Hook. In the useEffect() hook, we are setting our initial loading state to true, while this is true, our higher-order component will display a message. We are then creating a constant variable called user and assigning the API URL weâll be getting the repositories data from.
We are then making a basic fetch() request like we discussed above and then after the request is done we are setting the app loading state to false and populating the repos state with the data we got from the request.
return ( <div className='App'> <div className='container'> <h1>My Repositories</h1> </div> <div className='repo-container'> <ListLoading isLoading={AppState.loading} repos={AppState.repos} /> </div> </div> ); } export default App;
Here we are basically just rendering the Component we assigned our higher-order component to and also filling the isLoading prop and repos prop with their state value.
Now, we should see this in our browser, when the fetch request is still being made, courtesy of our withListLoading higher-order component:
(Large preview)
Now, when the fetch request has completed successfully, we should see the repositories displayed in a list format as below:
(Large preview)
Now, letâs style our project a little bit, in your App.css file, copy and paste this code.
@import url('https://fonts.Googleapis.com/css2?family=Amiri&display=swap'); :root { --basic-color: #23cc71; } .App { box-sizing: border-box; display: flex; justify-content: center; align-items: center; flex-direction: column; font-family: 'Amiri', serif; overflow: hidden; } .container { display: flex; flex-direction: row; } .container h1 { font-size: 60px; text-align: center; color: var(--basic-color); } .repo-container { width: 50%; height: 700px; margin: 50px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3); overflow: scroll; } @media screen and (max-width: 600px) { .repo-container { width: 100%; margin: 0; box-shadow: none; } } .repo-text { font-weight: 600; } .repo-description { font-weight: 600; font-style: bold; color: var(--basic-color); } .list-head { text-align: center; font-weight: 800; text-transform: uppercase; } .footer { font-size: 15px; font-weight: 600; } .list { list-style: circle; }
So in the code above, we are styling our app to look more pleasing to the eyes, we have assigned various class names to each element in our App.js file and thus we are using these class names to style our app.
Once weâve applied our styling, our app should look like this:
(Large preview)
Now our app looks much better.
So thatâs how we can use the Fetch API to consume a REST API. In the next section, weâll be discussing Axios and how we can use it to consume the same API in the same App.
Consuming APIs With Axios
Axios is an easy to use promise-based HTTP client for the browser and node.js. Since Axios is promise-based, we can take advantage of async and await for more readable and asynchronous code. With Axios, we get the ability to intercept and cancel request, it also has a built-in feature that provides client-side protection against cross-site request forgery.
Features Of Axios
Request and response interception
Streamlined error handling
Protection against XSRF
Support for upload progress
Response timeout
The ability to cancel requests
Support for older browsers
Automatic JSON data transformation
Making Requests With Axios
Making HTTP Requests with Axios is quite easy. The code below is basically how to make an HTTP request.
// Make a GET request axios({ method: 'get', url: 'https://api.github.com/users/hacktivist123', }); // Make a Post Request axios({ method: 'post', url: '/login', data: { firstName: 'shedrack', lastName: 'akintayo' } });
The code above shows the basic ways we can make a GET and POST HTTP request with Axios.
Axios also provides a set of shorthand method for performing different HTTP requests. The Methods are as follows:
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
For example, if we want to make a similar request like the example code above but with the shorthand methods we can do it like so:
// Make a GET request with a shorthand method axios.get('https://api.github.com/users/hacktivist123'); // Make a Post Request with a shorthand method axios.post('/signup', { firstName: 'shedrack', lastName: 'akintayo' });
In the code above, we are making the same request as what we did above but this time with the shorthand method. Axios provides flexibility and makes your HTTP requests even more readable.
Making Multiple Requests With Axios
Axios provides developers the ability to make and handle simultaneous HTTP requests using the axios.all() method. This method takes in an array of arguments and it returns a single promise object that resolves only when all arguments passed in the array have resolved.
For example, we can make multiple requests to the GitHub api using the axios.all() method like so:
axios.all([ axios.get('https://api.github.com/users/hacktivist123'), axios.get('https://api.github.com/users/adenekan41') ]) .then(response => { console.log('Date created: ', response[0].data.created_at); console.log('Date created: ', response[1].data.created_at); });
The code above makes simultaneous requests to an array of arguments in parallel and returns the response data, in our case, it will log to the console the created_at object from each of the API responses.
Letâs Consume A REST API With Axios Client
In this section, all weâll be doing is replacing fetch() method with Axios in our existing React Application. All we need to do is to install Axios and then use it in our App.js file for making the HTTP request to the GitHub API.
Now letâs install Axios in our React app by running either of the following:
With NPM:
npm install axios
With Yarn:
yarn add axios
After installation is complete, we have to import axios into our App.js. In our App.js weâll add the following line to the top of our App.js file:
import axios from 'axios'
After adding the line of code our App.js all we have to do inside our useEffect() is to write the following code:
useEffect(() => { setAppState({ loading: true }); const reposUrl = 'https://api.github.com/users/hacktivist123/repos'; axios.get(user).then((repos) => { const allRepos = repos.data; setAppState({ loading: false, repos: allRepos }); }); }, [setAppState]);
If youâve noticed, we have replaced the fetch API there with the Axios shorthand method axios.get to make a get request to the API.
axios.get(user).then((repos) => { const allRepos = repos.data; setAppState({ loading: false, repos: allRepos }); });
In this block of code, we are making a GET request then we are returning a promise that contains the repos data and assigning the data to a constant variable called allRepos. We are then setting the current loading state to false and also passing the data from the request to the repos state variable.
If we did everything correctly, we should see our app still render the same way without any change.
(Large preview)
So this is how we can use Axios client to consume a REST API.
Fetch vs Axios
In this section, I will be listing our certain features and then Iâll talk about how well Fetch and Axios support these features.
Basic Syntax Both Fetch and Axios have very simple syntaxes for making requests. But Axios has an upper hand because Axios automatically converts a response to JSON, so when using Axios we skip the step of converting the response to JSON, unlike Fetch() where weâd still have to convert the response to JSON. Lastly, Axios shorthand methods allow us to make specific HTTP Requests easier.
Browser Compatibility One of the many reasons why developers would prefer Axios over Fetch is because Axios is supported across major browsers and versions unlike Fetch that is only supported in Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+.
Handling Response Timeout Setting a timeout for responses is very easy to do in Axios by making use of the timeout option inside the request object. But in Fetch, it is not that easy to do this. Fetch provides a similar feature by using the AbortController() interface but it takes more time to implement and can get confusing.
Intercepting HTTP Requests Axios allows developers to intercept HTTP requests. HTTP interceptors are needed when we need to change HTTP requests from our application to the server. Interceptors give us the ability to do that without having to write extra code.
Making Multiple Requests Simultaneously Axios allows us to make multiple HTTP requests with the use of the axios.all() method ( I talked about this above). fetch() provides the same feature with the use of the promise.all() method, we can make multiple fetch() requests inside it.
Conclusion
Axios and fetch() are all great ways of consuming APIs but I advise you to use fetch() when building relatively small applications and make use of Axios when building large applications for scalability reasons. I hope you enjoyed working through this tutorial, you could always read more on Consuming REST APIs with either Fetch or Axios from the references below. If you have any questions, you can leave it in the comments section below and Iâll be happy to answer every single one.
Related Resources
(ks, ra, il)
Website Design & SEO Delray Beach by DBL07.co
Delray Beach SEO
source http://www.scpie.org/consuming-rest-apis-in-react-with-fetch-and-axios/ source https://scpie.tumblr.com/post/619994709782396928
0 notes
Text
Consuming REST APIs In React With Fetch And Axios
About The Author
Shedrack Akintayo is a software engineer from Lagos, Nigeria, who has a love for community building, open source and creating content and tech for the next ⌠More about Shedrack âŚ
If youâre a React developer whoâd like to learn how you can start consuming APIs in your React applications, then this article is for you. Shedrack Akintayo explains what a REST API is and how to build a simple application that consumes a REST API by using both Fetch API and Axios.
Consuming REST APIs in a React Application can be done in various ways, but in this tutorial, we will be discussing how we can consume REST APIs using two of the most popular methods known as Axios (a promise-based HTTP client) and Fetch API (a browser in-built web API). I will discuss and implement each of these methods in detail and shed light on some of the cool features each of them have to offer.
APIs are what we can use to supercharge our React applications with data. There are certain operations that canât be done on the client-side, so these operations are implemented on the server-side. We can then use the APIs to consume the data on the client-side.
APIs consist of a set of data, that is often in JSON format with specified endpoints. When we access data from an API, we want to access specific endpoints within that API framework. We can also say that an API is a contractual agreement between two services over the shape of request and response. The code is just a byproduct. It also contains the terms of this data exchange.
In React, there are various ways we can consume REST APIs in our applications, these ways include using the JavaScript inbuilt fetch() method and Axios which is a promise-based HTTP client for the browser and Node.js.
Note: A good knowledge of ReactJS, React Hooks, JavaScript and CSS will come in handy as you work your way throughout this tutorial.
Letâs get started with learning more about the REST API.
What Is A REST API
A REST API is an API that follows what is structured in accordance with the REST Structure for APIs. REST stands for âRepresentational State Transferâ. It consists of various rules that developers follow when creating APIs.
The Benefits Of REST APIs
Very easy to learn and understand;
It provides developers with the ability to organize complicated applications into simple resources;
It easy for external clients to build on your REST API without any complications;
It is very easy to scale;
A REST API is not language or platform-specific, but can be consumed with any language or run on any platform.
An Example Of A REST API Response
The way a REST API is structured depends on the product itâs been made for â but the rules of REST must be followed.
The sample response below is from the Github Open API. Weâll be using this API to build a React app later on in this tutorial.
{ "login": "hacktivist123", "id": 26572907, "node_id": "MDQ6VXNlcjI2NTcyOTA3", "avatar_url": "https://avatars3.githubusercontent.com/u/26572907?v=4", "gravatar_id": "", "url": "https://api.github.com/users/hacktivist123", "html_url": "https://github.com/hacktivist123", "followers_url": "https://api.github.com/users/hacktivist123/followers", "following_url": "https://api.github.com/users/hacktivist123/following{/other_user}", "gists_url": "https://api.github.com/users/hacktivist123/gists{/gist_id}", "starred_url": "https://api.github.com/users/hacktivist123/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/hacktivist123/subscriptions", "organizations_url": "https://api.github.com/users/hacktivist123/orgs", "repos_url": "https://api.github.com/users/hacktivist123/repos", "events_url": "https://api.github.com/users/hacktivist123/events{/privacy}", "received_events_url": "https://api.github.com/users/hacktivist123/received_events", "type": "User", "site_admin": false, "name": "Shedrack akintayo", "company": null, "blog": "https://sheddy.xyz", "location": "Lagos, Nigeria ", "email": null, "hireable": true, "bio": "â Software Engineer | | Developer AdvocateđĽ|| ⤠Everything JavaScript", "public_repos": 68, "public_gists": 1, "followers": 130, "following": 246, "created_at": "2017-03-21T12:55:48Z", "updated_at": "2020-05-11T13:02:57Z" }
The response above is from the Github REST API when I make a GET request to the following endpoint https://api.github.com/users/hacktivist123. It returns all the stored data about a user called hacktivist123. With this response, we can decide to render it whichever way we like in our React app.
Consuming APIs Using The Fetch API
The fetch() API is an inbuilt JavaScript method for getting resources from a server or an API endpoint. Itâs similar to XMLHttpRequest, but the fetch API provides a more powerful and flexible feature set.
It defines concepts such as CORS and the HTTP Origin header semantics, supplanting their separate definitions elsewhere.
The fetch() API method always takes in a compulsory argument, which is the path or URL to the resource you want to fetch. It returns a promise that points to the response from the request, whether the request is successful or not. You can also optionally pass in an init options object as the second argument.
Once a response has been fetched, there are several inbuilt methods available to define what the body content is and how it should be handled.
The Difference Between The Fetch API And jQuery Ajax
The Fetch API is different from jQuery Ajax in three main ways, which are:
The promise returned from a fetch() request will not reject when thereâs an HTTP error, no matter the nature of the response status. Instead, it will resolve the request normally, if the response status code is a 400 or 500 type code, itâll set the ok status. A request will only be rejected either because of network failure or if something is preventing the request from completing
fetch() will not allow the use of cross-site cookies i.e you cannot carry out a cross-site session using fetch()
fetch() will also not send cookies by default unless you set the credentials in the init option.
Parameters For The Fetch API
resource This is the path to the resource you want to fetch, this can either be a direct link to the resource path or a request object
init This is an object containing any custom setting or credentials youâll like to provide for your fetch() request. The following are a few of the possible options that can be contained in the init object:
method This is for specifying the HTTP request method e.g GET, POST, etc.
headers This is for specifying any headers you would like to add to your request, usually contained in an object or an object literal.
body This is for specifying a body that you want to add to your request: this can be a Blob, BufferSource, FormData, URLSearchParams, USVString, or ReadableStream object
mode This is for specifying the mode you want to use for the request, e.g., cors, no-cors, or same-origin.
credentials This for specifying the request credentials you want to use for the request, this option must be provided if you consider sending cookies automatically for the current domain.
Basic Syntax for Using the Fetch() API
A basic fetch request is really simple to write, take a look at the following code:
fetch('https://api.github.com/users/hacktivist123/repos') .then(response => response.json()) .then(data => console.log(data));
In the code above, we are fetching data from a URL that returns data as JSON and then printing it to the console. The simplest form of using fetch() often takes just one argument which is the path to the resource you want to fetch and then return a promise containing the response from the fetch request. This response is an object.
The response is just a regular HTTP response and not the actual JSON. In other to get the JSON body content from the response, weâd have to change the response to actual JSON using the json() method on the response.
Using Fetch API In React Apps
Using the Fetch API in React Apps is the normal way weâd use the Fetch API in javascript, there is no change in syntax, the only issue is deciding where to make the fetch request in our React app. Most fetch requests or any HTTP request of any sort is usually done in a React Component.
This request can either be made inside a Lifecycle Method if your component is a Class Component or inside a useEffect() React Hook if your component is a Functional Component.
For example, In the code below, we will make a fetch request inside a class component, which means weâll have to do it inside a lifecycle method. In this particular case, our fetch request will be made inside a componentDidMount lifecycle method because we want to make the request just after our React Component has mounted.
import React from 'react'; class myComponent extends React.Component { componentDidMount() { const apiUrl = 'https://api.github.com/users/hacktivist123/repos'; fetch(apiUrl) .then((response) => response.json()) .then((data) => console.log('This is your data', data)); } render() { return <h1>my Component has Mounted, Check the browser 'console' </h1>; } } export default myComponent;
In the code above, we are creating a very simple class component that makes a fetch request that logs the final data from the fetch request we have made to the API URL into the browser console after the React component has finished mounting.
The fetch() method takes in the path to the resource we want to fetch, which is assigned to a variable called apiUrl. After the fetch request has been completed it returns a promise that contains a response object. Then, we are extracting the JSON body content from the response using the json() method, finally we log the final data from the promise into the console.
Letâs Consume A REST API With Fetch Method
In this section, we will be building a simple react application that consumes an external API, we will be using the Fetch method to consume the API.
The simple application will display all the repositories and their description that belongs to a particular user. For this tutorial, Iâll be using my GitHub username, you can also use yours if you wish.
The first thing we need to do is to generate our React app by using create-react-app:
npx create-react-app myRepos
The command above will bootstrap a new React app for us. As soon as our new app has been created, all thatâs left to do is to run the following command and begin coding:
npm start
If our React is created properly we should see this in our browser window when we navigate to localhost:3000 after running the above command.
(Large preview)
In your src folder, create a new folder called component. This folder will hold all of our React components. In the new folder, create two files titled List.js and withListLoading.js. These two files will hold the components that will be needed in our app.
The List.js file will handle the display of our Repositories in the form of a list, and the withListLoading.js file will hold a higher-order component that will be displayed when the Fetch request we will be making is still ongoing.
In the List.js file we created inside the components folder, letâs paste in the following code:
import React from 'react'; const List = (props) => { const { repos } = props; if (repos.length === 0 || !repos) return <p>No repos, sorry</p>; return ( <ul> <h2 className='list-head'>Available Public Repositories</h2> {repos.map((repo) => { return ( <li key={repo.id} className='list'> <span className='repo-text'>{repo.name} </span> <span className='repo-description'>{repo.description}</span> </li> ); })} </ul> ); }; export default List;
The code above is a basic React list component that would display the data, in this case, the repositories name and their descriptions in a list.
Now, Let me explain the code bit by bit.
const { repos } = props;
We are initializing a prop for the component called repos.
if (repos.length === 0 || !repos) return <p>No repos, sorry</p>;
Here, all we are doing is making a conditional statement that will render a message when the length of the repos we get from the request we make is equal to zero.
return ( <ul> <h2 className='list-head'>Available Public Repositories</h2> {repos.map((repo) => { return ( <li key={repo.id} className='list'> <span className='repo-text'>{repo.name} </span> <span className='repo-description'>{repo.description}</span> </li> ); })} </ul> );
Here, we are mapping through each of the repositories that will be provided by the API request we make and extracting each of the repositories names and their descriptions then we are displaying each of them in a list.
export default List;
Here we are exporting our List component so that we can use it somewhere else.
In the withListLoading.js file we created inside the components folder, letâs paste in the following code:
import React from 'react'; function WithListLoading(Component) { return function WihLoadingComponent({ isLoading, ...props }) { if (!isLoading) return <Component {...props} />; return ( <p style=> Hold on, fetching data may take some time :) </p> ); }; } export default WithListLoading;
The code above is a higher-order React component that takes in another component and then returns some logic. In our case, our higher component will wait to check if the current isLoading state of the component it takes is true or false. If the current isLoading state is true, it will display a message Hold on, fetching data may take some time . Immediately the isLoading state changes to false itâll render the component it took in. In our case, itâll render the List component.
In your *App.js file inside the src folder, letâs paste in the following code:
import React, { useEffect, useState } from 'react'; import './App.css'; import List from './components/List'; import withListLoading from './components/withListLoading'; function App() { const ListLoading = withListLoading(List); const [appState, setAppState] = useState({ loading: false, repos: null, }); useEffect(() => { setAppState({ loading: true }); const user = `https://api.github.com/users/hacktivist123/repos`; fetch(user) .then((res) => res.json()) .then((repos) => { setAppState({ loading: false, repos: repos }); }); }, [setAppState]); return ( <div className='App'> <div className='container'> <h1>My Repositories</h1> </div> <div className='repo-container'> <ListLoading isLoading={appState.loading} repos={appState.repos} /> </div> <footer> <div className='footer'> Built{' '} <span role='img' aria-label='love'> đ </span>{' '} with by Shedrack Akintayo </div> </footer> </div> ); } export default App;
Our App.js is a functional component that makes use of React Hooks for handling state and also side effects. If youâre not familiar with React Hooks, read my Getting Started with React Hooks Guide.
Let me explain the code above bit by bit.
import React, { useEffect, useState } from 'react'; import './App.css'; import List from './components/List'; import withListLoading from './components/withListLoading';
Here, we are importing all the external files we need and also the components we created in our components folder. We are also importing the React Hooks we need from React.
const ListLoading = withListLoading(List); const [appState, setAppState] = useState({ loading: false, repos: null, });
Here, we are creating a new component called ListLoading and assigning our withListLoading higher-order component wrapped around our list component. We are then creating our state values loading and repos using the useState() React Hook.
useEffect(() => { setAppState({ loading: true }); const user = `https://api.github.com/users/hacktivist123/repos`; fetch(user) .then((res) => res.json()) .then((repos) => { setAppState({ loading: false, repos: repos }); }); }, [setAppState]);
Here, we are initializing a useEffect() React Hook. In the useEffect() hook, we are setting our initial loading state to true, while this is true, our higher-order component will display a message. We are then creating a constant variable called user and assigning the API URL weâll be getting the repositories data from.
We are then making a basic fetch() request like we discussed above and then after the request is done we are setting the app loading state to false and populating the repos state with the data we got from the request.
return ( <div className='App'> <div className='container'> <h1>My Repositories</h1> </div> <div className='repo-container'> <ListLoading isLoading={AppState.loading} repos={AppState.repos} /> </div> </div> ); } export default App;
Here we are basically just rendering the Component we assigned our higher-order component to and also filling the isLoading prop and repos prop with their state value.
Now, we should see this in our browser, when the fetch request is still being made, courtesy of our withListLoading higher-order component:
(Large preview)
Now, when the fetch request has completed successfully, we should see the repositories displayed in a list format as below:
(Large preview)
Now, letâs style our project a little bit, in your App.css file, copy and paste this code.
@import url('https://fonts.Googleapis.com/css2?family=Amiri&display=swap'); :root { --basic-color: #23cc71; } .App { box-sizing: border-box; display: flex; justify-content: center; align-items: center; flex-direction: column; font-family: 'Amiri', serif; overflow: hidden; } .container { display: flex; flex-direction: row; } .container h1 { font-size: 60px; text-align: center; color: var(--basic-color); } .repo-container { width: 50%; height: 700px; margin: 50px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3); overflow: scroll; } @media screen and (max-width: 600px) { .repo-container { width: 100%; margin: 0; box-shadow: none; } } .repo-text { font-weight: 600; } .repo-description { font-weight: 600; font-style: bold; color: var(--basic-color); } .list-head { text-align: center; font-weight: 800; text-transform: uppercase; } .footer { font-size: 15px; font-weight: 600; } .list { list-style: circle; }
So in the code above, we are styling our app to look more pleasing to the eyes, we have assigned various class names to each element in our App.js file and thus we are using these class names to style our app.
Once weâve applied our styling, our app should look like this:
(Large preview)
Now our app looks much better.
So thatâs how we can use the Fetch API to consume a REST API. In the next section, weâll be discussing Axios and how we can use it to consume the same API in the same App.
Consuming APIs With Axios
Axios is an easy to use promise-based HTTP client for the browser and node.js. Since Axios is promise-based, we can take advantage of async and await for more readable and asynchronous code. With Axios, we get the ability to intercept and cancel request, it also has a built-in feature that provides client-side protection against cross-site request forgery.
Features Of Axios
Request and response interception
Streamlined error handling
Protection against XSRF
Support for upload progress
Response timeout
The ability to cancel requests
Support for older browsers
Automatic JSON data transformation
Making Requests With Axios
Making HTTP Requests with Axios is quite easy. The code below is basically how to make an HTTP request.
// Make a GET request axios({ method: 'get', url: 'https://api.github.com/users/hacktivist123', }); // Make a Post Request axios({ method: 'post', url: '/login', data: { firstName: 'shedrack', lastName: 'akintayo' } });
The code above shows the basic ways we can make a GET and POST HTTP request with Axios.
Axios also provides a set of shorthand method for performing different HTTP requests. The Methods are as follows:
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
For example, if we want to make a similar request like the example code above but with the shorthand methods we can do it like so:
// Make a GET request with a shorthand method axios.get('https://api.github.com/users/hacktivist123'); // Make a Post Request with a shorthand method axios.post('/signup', { firstName: 'shedrack', lastName: 'akintayo' });
In the code above, we are making the same request as what we did above but this time with the shorthand method. Axios provides flexibility and makes your HTTP requests even more readable.
Making Multiple Requests With Axios
Axios provides developers the ability to make and handle simultaneous HTTP requests using the axios.all() method. This method takes in an array of arguments and it returns a single promise object that resolves only when all arguments passed in the array have resolved.
For example, we can make multiple requests to the GitHub api using the axios.all() method like so:
axios.all([ axios.get('https://api.github.com/users/hacktivist123'), axios.get('https://api.github.com/users/adenekan41') ]) .then(response => { console.log('Date created: ', response[0].data.created_at); console.log('Date created: ', response[1].data.created_at); });
The code above makes simultaneous requests to an array of arguments in parallel and returns the response data, in our case, it will log to the console the created_at object from each of the API responses.
Letâs Consume A REST API With Axios Client
In this section, all weâll be doing is replacing fetch() method with Axios in our existing React Application. All we need to do is to install Axios and then use it in our App.js file for making the HTTP request to the GitHub API.
Now letâs install Axios in our React app by running either of the following:
With NPM:
npm install axios
With Yarn:
yarn add axios
After installation is complete, we have to import axios into our App.js. In our App.js weâll add the following line to the top of our App.js file:
import axios from 'axios'
After adding the line of code our App.js all we have to do inside our useEffect() is to write the following code:
useEffect(() => { setAppState({ loading: true }); const reposUrl = 'https://api.github.com/users/hacktivist123/repos'; axios.get(user).then((repos) => { const allRepos = repos.data; setAppState({ loading: false, repos: allRepos }); }); }, [setAppState]);
If youâve noticed, we have replaced the fetch API there with the Axios shorthand method axios.get to make a get request to the API.
axios.get(user).then((repos) => { const allRepos = repos.data; setAppState({ loading: false, repos: allRepos }); });
In this block of code, we are making a GET request then we are returning a promise that contains the repos data and assigning the data to a constant variable called allRepos. We are then setting the current loading state to false and also passing the data from the request to the repos state variable.
If we did everything correctly, we should see our app still render the same way without any change.
(Large preview)
So this is how we can use Axios client to consume a REST API.
Fetch vs Axios
In this section, I will be listing our certain features and then Iâll talk about how well Fetch and Axios support these features.
Basic Syntax Both Fetch and Axios have very simple syntaxes for making requests. But Axios has an upper hand because Axios automatically converts a response to JSON, so when using Axios we skip the step of converting the response to JSON, unlike Fetch() where weâd still have to convert the response to JSON. Lastly, Axios shorthand methods allow us to make specific HTTP Requests easier.
Browser Compatibility One of the many reasons why developers would prefer Axios over Fetch is because Axios is supported across major browsers and versions unlike Fetch that is only supported in Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+.
Handling Response Timeout Setting a timeout for responses is very easy to do in Axios by making use of the timeout option inside the request object. But in Fetch, it is not that easy to do this. Fetch provides a similar feature by using the AbortController() interface but it takes more time to implement and can get confusing.
Intercepting HTTP Requests Axios allows developers to intercept HTTP requests. HTTP interceptors are needed when we need to change HTTP requests from our application to the server. Interceptors give us the ability to do that without having to write extra code.
Making Multiple Requests Simultaneously Axios allows us to make multiple HTTP requests with the use of the axios.all() method ( I talked about this above). fetch() provides the same feature with the use of the promise.all() method, we can make multiple fetch() requests inside it.
Conclusion
Axios and fetch() are all great ways of consuming APIs but I advise you to use fetch() when building relatively small applications and make use of Axios when building large applications for scalability reasons. I hope you enjoyed working through this tutorial, you could always read more on Consuming REST APIs with either Fetch or Axios from the references below. If you have any questions, you can leave it in the comments section below and Iâll be happy to answer every single one.
Related Resources
(ks, ra, il)
Website Design & SEO Delray Beach by DBL07.co
Delray Beach SEO
source http://www.scpie.org/consuming-rest-apis-in-react-with-fetch-and-axios/
0 notes
Text
Consuming REST APIs In React With Fetch And Axios
About The Author
Shedrack Akintayo is a software engineer from Lagos, Nigeria, who has a love for community building, open source and creating content and tech for the next ⌠More about Shedrack âŚ
If youâre a React developer whoâd like to learn how you can start consuming APIs in your React applications, then this article is for you. Shedrack Akintayo explains what a REST API is and how to build a simple application that consumes a REST API by using both Fetch API and Axios.
Consuming REST APIs in a React Application can be done in various ways, but in this tutorial, we will be discussing how we can consume REST APIs using two of the most popular methods known as Axios (a promise-based HTTP client) and Fetch API (a browser in-built web API). I will discuss and implement each of these methods in detail and shed light on some of the cool features each of them have to offer.
APIs are what we can use to supercharge our React applications with data. There are certain operations that canât be done on the client-side, so these operations are implemented on the server-side. We can then use the APIs to consume the data on the client-side.
APIs consist of a set of data, that is often in JSON format with specified endpoints. When we access data from an API, we want to access specific endpoints within that API framework. We can also say that an API is a contractual agreement between two services over the shape of request and response. The code is just a byproduct. It also contains the terms of this data exchange.
In React, there are various ways we can consume REST APIs in our applications, these ways include using the JavaScript inbuilt fetch() method and Axios which is a promise-based HTTP client for the browser and Node.js.
Note: A good knowledge of ReactJS, React Hooks, JavaScript and CSS will come in handy as you work your way throughout this tutorial.
Letâs get started with learning more about the REST API.
What Is A REST API
A REST API is an API that follows what is structured in accordance with the REST Structure for APIs. REST stands for âRepresentational State Transferâ. It consists of various rules that developers follow when creating APIs.
The Benefits Of REST APIs
Very easy to learn and understand;
It provides developers with the ability to organize complicated applications into simple resources;
It easy for external clients to build on your REST API without any complications;
It is very easy to scale;
A REST API is not language or platform-specific, but can be consumed with any language or run on any platform.
An Example Of A REST API Response
The way a REST API is structured depends on the product itâs been made for â but the rules of REST must be followed.
The sample response below is from the Github Open API. Weâll be using this API to build a React app later on in this tutorial.
{ "login": "hacktivist123", "id": 26572907, "node_id": "MDQ6VXNlcjI2NTcyOTA3", "avatar_url": "https://avatars3.githubusercontent.com/u/26572907?v=4", "gravatar_id": "", "url": "https://api.github.com/users/hacktivist123", "html_url": "https://github.com/hacktivist123", "followers_url": "https://api.github.com/users/hacktivist123/followers", "following_url": "https://api.github.com/users/hacktivist123/following{/other_user}", "gists_url": "https://api.github.com/users/hacktivist123/gists{/gist_id}", "starred_url": "https://api.github.com/users/hacktivist123/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/hacktivist123/subscriptions", "organizations_url": "https://api.github.com/users/hacktivist123/orgs", "repos_url": "https://api.github.com/users/hacktivist123/repos", "events_url": "https://api.github.com/users/hacktivist123/events{/privacy}", "received_events_url": "https://api.github.com/users/hacktivist123/received_events", "type": "User", "site_admin": false, "name": "Shedrack akintayo", "company": null, "blog": "https://sheddy.xyz", "location": "Lagos, Nigeria ", "email": null, "hireable": true, "bio": "â Software Engineer | | Developer AdvocateđĽ|| ⤠Everything JavaScript", "public_repos": 68, "public_gists": 1, "followers": 130, "following": 246, "created_at": "2017-03-21T12:55:48Z", "updated_at": "2020-05-11T13:02:57Z" }
The response above is from the Github REST API when I make a GET request to the following endpoint https://api.github.com/users/hacktivist123. It returns all the stored data about a user called hacktivist123. With this response, we can decide to render it whichever way we like in our React app.
Consuming APIs Using The Fetch API
The fetch() API is an inbuilt JavaScript method for getting resources from a server or an API endpoint. Itâs similar to XMLHttpRequest, but the fetch API provides a more powerful and flexible feature set.
It defines concepts such as CORS and the HTTP Origin header semantics, supplanting their separate definitions elsewhere.
The fetch() API method always takes in a compulsory argument, which is the path or URL to the resource you want to fetch. It returns a promise that points to the response from the request, whether the request is successful or not. You can also optionally pass in an init options object as the second argument.
Once a response has been fetched, there are several inbuilt methods available to define what the body content is and how it should be handled.
The Difference Between The Fetch API And jQuery Ajax
The Fetch API is different from jQuery Ajax in three main ways, which are:
The promise returned from a fetch() request will not reject when thereâs an HTTP error, no matter the nature of the response status. Instead, it will resolve the request normally, if the response status code is a 400 or 500 type code, itâll set the ok status. A request will only be rejected either because of network failure or if something is preventing the request from completing
fetch() will not allow the use of cross-site cookies i.e you cannot carry out a cross-site session using fetch()
fetch() will also not send cookies by default unless you set the credentials in the init option.
Parameters For The Fetch API
resource This is the path to the resource you want to fetch, this can either be a direct link to the resource path or a request object
init This is an object containing any custom setting or credentials youâll like to provide for your fetch() request. The following are a few of the possible options that can be contained in the init object:
method This is for specifying the HTTP request method e.g GET, POST, etc.
headers This is for specifying any headers you would like to add to your request, usually contained in an object or an object literal.
body This is for specifying a body that you want to add to your request: this can be a Blob, BufferSource, FormData, URLSearchParams, USVString, or ReadableStream object
mode This is for specifying the mode you want to use for the request, e.g., cors, no-cors, or same-origin.
credentials This for specifying the request credentials you want to use for the request, this option must be provided if you consider sending cookies automatically for the current domain.
Basic Syntax for Using the Fetch() API
A basic fetch request is really simple to write, take a look at the following code:
fetch('https://api.github.com/users/hacktivist123/repos') .then(response => response.json()) .then(data => console.log(data));
In the code above, we are fetching data from a URL that returns data as JSON and then printing it to the console. The simplest form of using fetch() often takes just one argument which is the path to the resource you want to fetch and then return a promise containing the response from the fetch request. This response is an object.
The response is just a regular HTTP response and not the actual JSON. In other to get the JSON body content from the response, weâd have to change the response to actual JSON using the json() method on the response.
Using Fetch API In React Apps
Using the Fetch API in React Apps is the normal way weâd use the Fetch API in javascript, there is no change in syntax, the only issue is deciding where to make the fetch request in our React app. Most fetch requests or any HTTP request of any sort is usually done in a React Component.
This request can either be made inside a Lifecycle Method if your component is a Class Component or inside a useEffect() React Hook if your component is a Functional Component.
For example, In the code below, we will make a fetch request inside a class component, which means weâll have to do it inside a lifecycle method. In this particular case, our fetch request will be made inside a componentDidMount lifecycle method because we want to make the request just after our React Component has mounted.
import React from 'react'; class myComponent extends React.Component { componentDidMount() { const apiUrl = 'https://api.github.com/users/hacktivist123/repos'; fetch(apiUrl) .then((response) => response.json()) .then((data) => console.log('This is your data', data)); } render() { return <h1>my Component has Mounted, Check the browser 'console' </h1>; } } export default myComponent;
In the code above, we are creating a very simple class component that makes a fetch request that logs the final data from the fetch request we have made to the API URL into the browser console after the React component has finished mounting.
The fetch() method takes in the path to the resource we want to fetch, which is assigned to a variable called apiUrl. After the fetch request has been completed it returns a promise that contains a response object. Then, we are extracting the JSON body content from the response using the json() method, finally we log the final data from the promise into the console.
Letâs Consume A REST API With Fetch Method
In this section, we will be building a simple react application that consumes an external API, we will be using the Fetch method to consume the API.
The simple application will display all the repositories and their description that belongs to a particular user. For this tutorial, Iâll be using my GitHub username, you can also use yours if you wish.
The first thing we need to do is to generate our React app by using create-react-app:
npx create-react-app myRepos
The command above will bootstrap a new React app for us. As soon as our new app has been created, all thatâs left to do is to run the following command and begin coding:
npm start
If our React is created properly we should see this in our browser window when we navigate to localhost:3000 after running the above command.
(Large preview)
In your src folder, create a new folder called component. This folder will hold all of our React components. In the new folder, create two files titled List.js and withListLoading.js. These two files will hold the components that will be needed in our app.
The List.js file will handle the display of our Repositories in the form of a list, and the withListLoading.js file will hold a higher-order component that will be displayed when the Fetch request we will be making is still ongoing.
In the List.js file we created inside the components folder, letâs paste in the following code:
import React from 'react'; const List = (props) => { const { repos } = props; if (repos.length === 0 || !repos) return <p>No repos, sorry</p>; return ( <ul> <h2 className='list-head'>Available Public Repositories</h2> {repos.map((repo) => { return ( <li key={repo.id} className='list'> <span className='repo-text'>{repo.name} </span> <span className='repo-description'>{repo.description}</span> </li> ); })} </ul> ); }; export default List;
The code above is a basic React list component that would display the data, in this case, the repositories name and their descriptions in a list.
Now, Let me explain the code bit by bit.
const { repos } = props;
We are initializing a prop for the component called repos.
if (repos.length === 0 || !repos) return <p>No repos, sorry</p>;
Here, all we are doing is making a conditional statement that will render a message when the length of the repos we get from the request we make is equal to zero.
return ( <ul> <h2 className='list-head'>Available Public Repositories</h2> {repos.map((repo) => { return ( <li key={repo.id} className='list'> <span className='repo-text'>{repo.name} </span> <span className='repo-description'>{repo.description}</span> </li> ); })} </ul> );
Here, we are mapping through each of the repositories that will be provided by the API request we make and extracting each of the repositories names and their descriptions then we are displaying each of them in a list.
export default List;
Here we are exporting our List component so that we can use it somewhere else.
In the withListLoading.js file we created inside the components folder, letâs paste in the following code:
import React from 'react'; function WithListLoading(Component) { return function WihLoadingComponent({ isLoading, ...props }) { if (!isLoading) return <Component {...props} />; return ( <p style=> Hold on, fetching data may take some time :) </p> ); }; } export default WithListLoading;
The code above is a higher-order React component that takes in another component and then returns some logic. In our case, our higher component will wait to check if the current isLoading state of the component it takes is true or false. If the current isLoading state is true, it will display a message Hold on, fetching data may take some time . Immediately the isLoading state changes to false itâll render the component it took in. In our case, itâll render the List component.
In your *App.js file inside the src folder, letâs paste in the following code:
import React, { useEffect, useState } from 'react'; import './App.css'; import List from './components/List'; import withListLoading from './components/withListLoading'; function App() { const ListLoading = withListLoading(List); const [appState, setAppState] = useState({ loading: false, repos: null, }); useEffect(() => { setAppState({ loading: true }); const user = `https://api.github.com/users/hacktivist123/repos`; fetch(user) .then((res) => res.json()) .then((repos) => { setAppState({ loading: false, repos: repos }); }); }, [setAppState]); return ( <div className='App'> <div className='container'> <h1>My Repositories</h1> </div> <div className='repo-container'> <ListLoading isLoading={appState.loading} repos={appState.repos} /> </div> <footer> <div className='footer'> Built{' '} <span role='img' aria-label='love'> đ </span>{' '} with by Shedrack Akintayo </div> </footer> </div> ); } export default App;
Our App.js is a functional component that makes use of React Hooks for handling state and also side effects. If youâre not familiar with React Hooks, read my Getting Started with React Hooks Guide.
Let me explain the code above bit by bit.
import React, { useEffect, useState } from 'react'; import './App.css'; import List from './components/List'; import withListLoading from './components/withListLoading';
Here, we are importing all the external files we need and also the components we created in our components folder. We are also importing the React Hooks we need from React.
const ListLoading = withListLoading(List); const [appState, setAppState] = useState({ loading: false, repos: null, });
Here, we are creating a new component called ListLoading and assigning our withListLoading higher-order component wrapped around our list component. We are then creating our state values loading and repos using the useState() React Hook.
useEffect(() => { setAppState({ loading: true }); const user = `https://api.github.com/users/hacktivist123/repos`; fetch(user) .then((res) => res.json()) .then((repos) => { setAppState({ loading: false, repos: repos }); }); }, [setAppState]);
Here, we are initializing a useEffect() React Hook. In the useEffect() hook, we are setting our initial loading state to true, while this is true, our higher-order component will display a message. We are then creating a constant variable called user and assigning the API URL weâll be getting the repositories data from.
We are then making a basic fetch() request like we discussed above and then after the request is done we are setting the app loading state to false and populating the repos state with the data we got from the request.
return ( <div className='App'> <div className='container'> <h1>My Repositories</h1> </div> <div className='repo-container'> <ListLoading isLoading={AppState.loading} repos={AppState.repos} /> </div> </div> ); } export default App;
Here we are basically just rendering the Component we assigned our higher-order component to and also filling the isLoading prop and repos prop with their state value.
Now, we should see this in our browser, when the fetch request is still being made, courtesy of our withListLoading higher-order component:
(Large preview)
Now, when the fetch request has completed successfully, we should see the repositories displayed in a list format as below:
(Large preview)
Now, letâs style our project a little bit, in your App.css file, copy and paste this code.
@import url('https://fonts.Googleapis.com/css2?family=Amiri&display=swap'); :root { --basic-color: #23cc71; } .App { box-sizing: border-box; display: flex; justify-content: center; align-items: center; flex-direction: column; font-family: 'Amiri', serif; overflow: hidden; } .container { display: flex; flex-direction: row; } .container h1 { font-size: 60px; text-align: center; color: var(--basic-color); } .repo-container { width: 50%; height: 700px; margin: 50px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3); overflow: scroll; } @media screen and (max-width: 600px) { .repo-container { width: 100%; margin: 0; box-shadow: none; } } .repo-text { font-weight: 600; } .repo-description { font-weight: 600; font-style: bold; color: var(--basic-color); } .list-head { text-align: center; font-weight: 800; text-transform: uppercase; } .footer { font-size: 15px; font-weight: 600; } .list { list-style: circle; }
So in the code above, we are styling our app to look more pleasing to the eyes, we have assigned various class names to each element in our App.js file and thus we are using these class names to style our app.
Once weâve applied our styling, our app should look like this:
(Large preview)
Now our app looks much better.
So thatâs how we can use the Fetch API to consume a REST API. In the next section, weâll be discussing Axios and how we can use it to consume the same API in the same App.
Consuming APIs With Axios
Axios is an easy to use promise-based HTTP client for the browser and node.js. Since Axios is promise-based, we can take advantage of async and await for more readable and asynchronous code. With Axios, we get the ability to intercept and cancel request, it also has a built-in feature that provides client-side protection against cross-site request forgery.
Features Of Axios
Request and response interception
Streamlined error handling
Protection against XSRF
Support for upload progress
Response timeout
The ability to cancel requests
Support for older browsers
Automatic JSON data transformation
Making Requests With Axios
Making HTTP Requests with Axios is quite easy. The code below is basically how to make an HTTP request.
// Make a GET request axios({ method: 'get', url: 'https://api.github.com/users/hacktivist123', }); // Make a Post Request axios({ method: 'post', url: '/login', data: { firstName: 'shedrack', lastName: 'akintayo' } });
The code above shows the basic ways we can make a GET and POST HTTP request with Axios.
Axios also provides a set of shorthand method for performing different HTTP requests. The Methods are as follows:
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
For example, if we want to make a similar request like the example code above but with the shorthand methods we can do it like so:
// Make a GET request with a shorthand method axios.get('https://api.github.com/users/hacktivist123'); // Make a Post Request with a shorthand method axios.post('/signup', { firstName: 'shedrack', lastName: 'akintayo' });
In the code above, we are making the same request as what we did above but this time with the shorthand method. Axios provides flexibility and makes your HTTP requests even more readable.
Making Multiple Requests With Axios
Axios provides developers the ability to make and handle simultaneous HTTP requests using the axios.all() method. This method takes in an array of arguments and it returns a single promise object that resolves only when all arguments passed in the array have resolved.
For example, we can make multiple requests to the GitHub api using the axios.all() method like so:
axios.all([ axios.get('https://api.github.com/users/hacktivist123'), axios.get('https://api.github.com/users/adenekan41') ]) .then(response => { console.log('Date created: ', response[0].data.created_at); console.log('Date created: ', response[1].data.created_at); });
The code above makes simultaneous requests to an array of arguments in parallel and returns the response data, in our case, it will log to the console the created_at object from each of the API responses.
Letâs Consume A REST API With Axios Client
In this section, all weâll be doing is replacing fetch() method with Axios in our existing React Application. All we need to do is to install Axios and then use it in our App.js file for making the HTTP request to the GitHub API.
Now letâs install Axios in our React app by running either of the following:
With NPM:
npm install axios
With Yarn:
yarn add axios
After installation is complete, we have to import axios into our App.js. In our App.js weâll add the following line to the top of our App.js file:
import axios from 'axios'
After adding the line of code our App.js all we have to do inside our useEffect() is to write the following code:
useEffect(() => { setAppState({ loading: true }); const reposUrl = 'https://api.github.com/users/hacktivist123/repos'; axios.get(user).then((repos) => { const allRepos = repos.data; setAppState({ loading: false, repos: allRepos }); }); }, [setAppState]);
If youâve noticed, we have replaced the fetch API there with the Axios shorthand method axios.get to make a get request to the API.
axios.get(user).then((repos) => { const allRepos = repos.data; setAppState({ loading: false, repos: allRepos }); });
In this block of code, we are making a GET request then we are returning a promise that contains the repos data and assigning the data to a constant variable called allRepos. We are then setting the current loading state to false and also passing the data from the request to the repos state variable.
If we did everything correctly, we should see our app still render the same way without any change.
(Large preview)
So this is how we can use Axios client to consume a REST API.
Fetch vs Axios
In this section, I will be listing our certain features and then Iâll talk about how well Fetch and Axios support these features.
Basic Syntax Both Fetch and Axios have very simple syntaxes for making requests. But Axios has an upper hand because Axios automatically converts a response to JSON, so when using Axios we skip the step of converting the response to JSON, unlike Fetch() where weâd still have to convert the response to JSON. Lastly, Axios shorthand methods allow us to make specific HTTP Requests easier.
Browser Compatibility One of the many reasons why developers would prefer Axios over Fetch is because Axios is supported across major browsers and versions unlike Fetch that is only supported in Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+.
Handling Response Timeout Setting a timeout for responses is very easy to do in Axios by making use of the timeout option inside the request object. But in Fetch, it is not that easy to do this. Fetch provides a similar feature by using the AbortController() interface but it takes more time to implement and can get confusing.
Intercepting HTTP Requests Axios allows developers to intercept HTTP requests. HTTP interceptors are needed when we need to change HTTP requests from our application to the server. Interceptors give us the ability to do that without having to write extra code.
Making Multiple Requests Simultaneously Axios allows us to make multiple HTTP requests with the use of the axios.all() method ( I talked about this above). fetch() provides the same feature with the use of the promise.all() method, we can make multiple fetch() requests inside it.
Conclusion
Axios and fetch() are all great ways of consuming APIs but I advise you to use fetch() when building relatively small applications and make use of Axios when building large applications for scalability reasons. I hope you enjoyed working through this tutorial, you could always read more on Consuming REST APIs with either Fetch or Axios from the references below. If you have any questions, you can leave it in the comments section below and Iâll be happy to answer every single one.
Related Resources
(ks, ra, il)
Website Design & SEO Delray Beach by DBL07.co
Delray Beach SEO
source http://www.scpie.org/consuming-rest-apis-in-react-with-fetch-and-axios/ source https://scpie1.blogspot.com/2020/06/consuming-rest-apis-in-react-with-fetch.html
0 notes
Text
Reading file with FileReader in JavaScript + Reading Excel SpreadSheets
The file input field for uploading the file. This should be inside the <form> tag. It should have enctype="multipart/formdata" when using vanilla JS. React doesn't seem to need this.
<input type="file" name="excelFile"/>
Add an onChange action to hook up a file upload action.
Capturing the file:
let file = event.target.files[0];
File is an object with name, size and various attributes.
Use the FileReader class to create a new reader to make the reading and stuff.
let reader = new FileReader(); // Reading text and csv files: reader.readAsText(file); // Reading complex files like xls files reader.readAsArrayBuffer(file);
Hook into the onload event listener that will fire after the file is being loaded.
reader.onload = function(evt) { var data = evt.target.result; // Do something with the data, display it // OR var { result } = reader; // Do something with it // The data and the result is the same thing }
Reading Excel SpreadSheet xls, xlsx with XLSX module
Get array buffer data and process the spreadsheet with this module.
npm i xlsx
import XLSX from 'xlsx';
Now use the following functions to parse the excel sheet and convert the data into a JSON object:
// Parses the data var workbook = XLSX.read(data, {type: 'array'}); // array because I used readAsArrayBuffer // It can have multiple sheets, here taking the first one var first_worksheet = workbook.Sheets[workbook.SheetNames[0]]; // Converting the worksheet to json var jsonArr = XLSX.utils.sheet_to_json(first_worksheet, { header: 1 }); // Do something with the json
XLSX also works with csv and text files.
0 notes
Text
How to Send Form Data Using Axios Post Request in React

Sending form data from a React application to a server is a common task, and Axios is a popular library for making HTTP requests in React. In this blog post, weâll walk you through the process of sending form data using an Axios POST request in a React application. Weâll provide you with a practical example to illustrate each step.
Prerequisites:
Before we start, ensure you have the following prerequisites in place:
A basic understanding of React.
Node.js and npm (Node Package Manager) installed on your system.
A code editor of your choice (e.g., Visual Studio Code).
Step 1: Set Up a React Project
If you donât already have a React project, you can create one using Create React App. Open your terminal and run the following command:
npx create-react-app axios-form-example
Once the project is created, navigate to the project directory:
cd axios-form-example
Step 2: Install Axios To use Axios in your React project, you need to install it. Run the following command:
npm install axios
Step 3: Create a Form Component
In your React project, create a new component for the form. You can name it Form.js. Hereâs a simple example of a form component:
// src/Form.js
import React, { useState } from 'react';
import axios from 'axios';
function Form() {
const [formData, setFormData] = useState({
name: '',
email: '',
});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post('YOUR_API_ENDPOINT', formData);
console.log('Form data submitted successfully:', response.data);
} catch (error) {
console.error('Error submitting form data:', error);
}
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
/>
</label>
<br />
<label>
Email:
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
/>
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}
export default Form;
In this component, we define a form with two input fields (name and email). We use the useState hook to manage the form data, and Axios to make the POST request when the form is submitted. Step 4: Import and Use the Form Component Import and use the Form component in your App.js file:
// src/App.js
import React from 'react';
import Form from './Form';
function App() {
return (
<div className="App">
<h1>React Form with Axios POST Request</h1>
<Form />
</div>
);
}
export default App;
Step 5: Replace âYOUR_API_ENDPOINTâ
In the Form.js component, replace 'YOUR_API_ENDPOINT' with the actual endpoint where you want to send the form data.
Step 6: Run Your React App
Finally, run your React application using the following command:
npm start
Your React app should now be running, and you can access it in your browser. Fill out the form, click the âSubmitâ button, and you should see the form data being sent to the specified API endpoint in the browserâs console.
Conclusion:
In this blog post, weâve demonstrated how to send form data using an Axios POST request in a React application. By following the steps outlined above, you can easily integrate form submissions with server-side endpoints and handle data efficiently in your React projects. Sending data from your React app to a server has never been more straightforward, thanks to Axios.
The React Company is your trusted resource for all things React. Whether youâre a beginner looking to learn React or an experienced developer seeking solutions to common challenges, weâve got you covered.
Contact us for more details, and letâs collaborate to elevate your React skills to the next level.
0 notes
Text
Best Practices With React Hooks
About The Author
Adeneye David Abiodun is a JavaScript lover and a Tech Enthusiast, Founded @corperstechhub and currently a Lecturer / IT Technologist @critm_ugep. I build ⌠More about Adeneye âŚ
This article covers the rules of React Hooks and how to effectively start using them in your projects. Please note that in order to follow this article in detail, you will need to know how to use React Hooks.
React Hooks are a new addition in React 16.8 that let you use state and other React features without writing a class component. In other words, Hooks are functions that let you âhook intoâ React state and lifecycle features from function components. (They do not work inside class components.)
React provides a few built-in Hooks like useState. You can also create your own Hooks to reuse stateful behavior between different components. The example below shows a counter whose state is managed using the useState() hook. Each time you click on the button, we make use of setCount() to update the value of count by 1.
See the Pen [React Hook example with Counter](https://codepen.io/smashingmag/pen/QWbXMyM) by Adeneye Abiodun David.
See the Pen React Hook example with Counter by Adeneye Abiodun David.
This example renders a counter with a value of 0. When you click the button, it increments the value by 1. The initial value of the component is defined using useState.
const [count, setCount] = useState(0)
As you can see, we set that to be 0. Then we use the onClick() method to call setCount when we want to increment the value.
<button onClick={() => setCount(count + 1)}> Click me </button>
Before the release of React Hooks, this example would have used more lines of code, as weâd have had to make use of a class component.
Rules Of React Hooks
Before we dive deep into the best practices, we need to understand the rules of React Hooks which are also some of the fundamental concepts of the practices presented in this article.
React Hooks are JavaScript functions, but you need to follow two rules when using them.
Call Hooks at the top level;
Only call Hooks from React components.
Note: These two rules were introduced in React Hooks, as opposed to being part of JavaScript itself.
Letâs look at these rules in more detail.
Call Hooks At The Top Level
Donât call Hooks inside loops, conditions, or nested functions. Always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. Thatâs what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.
Letâs make a Form component which will have two states:
accountName
accountDetail
These states will have default values, weâll make use of the useEffect hook to persist the state to either the local storage of our browser or to the title of our document.
Now, this component will be maybe to successfully manage its state if it remains the same between multiple calls of useState and useEffect.
function Form() { // 1. Use the accountName state variable const [accountName, setAccountName] = useState('David'); // 2. Use an effect for persisting the form useEffect(function persistForm() { localStorage.setItem('formData', accountName); }); // 3. Use the accountDetail state variable const [accountDetail, setAccountDetail] = useState('Active'); // 4. Use an effect for updating the title useEffect(function updateStatus() { document.title = accountName + ' ' + accountDetail; }); // ... }
If the order of our Hooks changes (which can be possible when they are called in loops or conditionals), React will have a hard time figuring out how to preserve the state of our component.
// ------------ useState('David') // 1. Initialize the accountName state variable with 'David' useEffect(persistForm) // 2. Add an effect for persisting the form useState('Active') // 3. Initialize the accountdetail state variable with 'Active' useEffect(updateStatus) // 4. Add an effect for updating the status // ------------- // Second render // ------------- useState('David') // 1. Read the accountName state variable (argument is ignored) useEffect(persistForm) // 2. Replace the effect for persisting the form useState('Active') // 3. Read the accountDetail state variable (argument is ignored) useEffect(updateStatus) // 4. Replace the effect for updating the status // ...
Thatâs the order React follows to call our hooks. Since the order remains the same, it will be able to preserve the state of our component. But what happens if we put a Hook call inside a condition?
// đ´ We're breaking the first rule by using a Hook in a condition if (accountName !== '') { useEffect(function persistForm() { localStorage.setItem('formData', accountName); }); }
The accountName !== '' condition is true on the first render, so we run this Hook. However, on the next render the user might clear the form, making the condition false. Now that we skip this Hook during rendering, the order of the Hook calls becomes different:
useState('David') // 1. Read the accountName state variable (argument is ignored) // useEffect(persistForm) // đ´ This Hook was skipped! useState('Active') // đ´ 2 (but was 3). Fail to read the accountDetails state variable useEffect(updateStatus) // đ´ 3 (but was 4). Fail to replace the effect
React wouldnât know what to return for the second useState Hook call. React expected that the second Hook call in this component corresponds to the persistForm effect, just like during the previous render â but it doesnât anymore. From that point on, every next Hook call after the one we skipped would also shift by one â leading to bugs.
This is why Hooks must be called on the top level of our components. If we want to run an effect conditionally, we can put that condition inside our Hook.
Note: Check out the React Hook docs to read more on this topic.
Only Call Hooks From React Components
Donât call Hooks from regular JavaScript functions. Instead, you can call Hooks from React function components. Letâs take look at the difference between JavaScript function and React component below:
JavaScript Function
import { useState } = "react"; function toCelsius(fahrenheit) { const [name, setName] = useState("David"); return (5/9) * (fahrenheit-32); } document.getElementById("demo").innerHTML = toCelsius;
Here we import the useState hook from the React package, and then declared our function. But this is invalid as it is not a React component.
React Function
import React, { useState} from "react"; import ReactDOM from "react-dom"; function Account(props) { const [name, setName] = useState("David"); return <p>Hello, {name}! The price is <b>{props.total}</b> and the total amount is <b>{props.amount}</b></p> } ReactDom.render( <Account total={20} amount={5000} />, document.getElementById('root') );
Even though the body of both looks similar, the latter becomes a component when we import React into the file. This is what makes it possible for us to use things like JSX and React hooks inside.
If you happened to import your preferred hook without importing React (which makes it a regular function), you will not be able to make use of the Hook youâve imported as the Hook is accessible only in React component.
Call Hooks From Custom Hooks
A custom Hook is a JavaScript function whose name starts with use and that may call other Hooks. For example, useUserName is used below a custom Hook that calls the useState and useEffect hooks. It fetches data from an API, loops through the data, and calls setIsPresent() if the specific username it received is present in the API data.
export default function useUserName(userName) { const [isPresent, setIsPresent] = useState(false); useEffect(() => { const data = MockedApi.fetchData(); data.then((res) => { res.forEach((e) => { if (e.name === userName) { setIsPresent(true); } }); }); }); return isPresent; }
We can then go on to reuse the functionality of this hook in other places where we need such in our application. In such places, except when needed, we donât have to call useState or useEffect anymore.
By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code.
ESLint Plugin
ESLint plugin called eslint-plugin-react-hooks enforces the rules above. This comes in handy in enforcing the rules when working on a project. I suggest you make use of this plugin when working on your project, especially when working with others. You can add this plugin to your project if youâd like to try it:
// Your ESLint configuration { "plugins": [ // ... "react-hooks" ], "rules": { // ... "react-hooks/rules-of-hooks": "error", // Checks rules of Hooks "react-hooks/exhaustive-deps": "warn" // Checks effect dependencies } }
This plugin is included by default in Create React App. So you donât need to add it if you bootstrap your React applications using Create-React-App.
Thinking In Hooks
Letâs take a brief look at class components and functional components (with Hooks), before diving into the few Hooks best practices.
The simplest way to define a component in React is to write a JavaScript function that returns a React element:
function Welcome(props) { return <h1>Hello, {props.name}</h1>; }
The Welcome component accepts props which is an object that contains data and returns a React element. We can then import and render this component in another component.
The class component uses a programming methodology called Encapsulation which basically means that everything relevant to the class component will live within it. Life-cycle methods (constructors, componentDidMount(), render, and so on) give components a predictable structure.
Encapsulation is one of the fundamentals of OOP (Object-Oriented Programming). It refers to the bundling of data within the methods that operate on that data, and is used to hide the values or state of a structured data object inside a class â preventing unauthorized partiesâ direct access to them.
With Hooks, the composition of a component changes from being a combination of life-cycle Hooks â to functionalities with some render at the end.
Function Component
The example below shows how custom Hooks can be used in a functional component (without showcasing what the body is). However, what it does or can do is not limited. It could be instantiating state variables, consuming contexts, subscribing the component to various side effects â or all of the above if youâre using a custom hook!
function { useHook{...}; useHook{...}; useHook{...}; return (
...
); }
Class Component
A class component requires you to extend from React.Component and create a render function which returns a React element. This requires more code but will also give you some benefits.
class { constructor(props) {...} componentDidMount() {...} componentWillUnmount() {...} render() {...} }
There are some benefits you get by using functional components in React:
It will get easier to separate container and presentational components because you need to think more about your componentâs state if you donât have access to setState() in your component.
Functional components are much easier to read and test because they are plain JavaScript functions without state or lifecycle-hooks.
You end up with less code.
The React team mentioned that there may be a performance boost for functional components in future React versions.
This leads to the first best practice when using React Hooks.
Hooks Best Practices
1. Simplify Your Hooks
Keeping React Hooks simple will give you the power to effectively control and manipulate what goes on in a component throughout its lifetime. Avoid writing custom Hooks as much as possible; you can inline a useState() or useEffect() instead of creating your own hook.
If you find yourself making use of a bunch of custom Hooks that are related in functionality, you can create a custom hook that acts as a wrapper for these. Letâs take a look at two different functional components with hooks below.
Functional Component v1
function { useHook(...); useHook(...); useHook(...); return( <div>...</div> ); }
Functional Component v2
function { useCustomHook(...); useHook(...); useHook(...); return( <div>...</div> ); }
v2 is a better version because it keeps the hook simple and all other useHooks are inline accordingly. This allows us to create functionality that can be reused across different components and also gives us more power to control and manipulate our components effectively. Instead of adopting v1 in which our components are littered with Hooks, you should make use of v2 which will make debugging easy and your code cleaner.
2. Organize And Structure Your Hooks
One of the advantages of React Hooks is the ability to write less code that is easy to read. In some cases, the amount of useEffect() and useState() can still be confusing. When you keep your component organized it will help in readability and keep the flow of your components consistent and predictable. If your custom Hooks are too complicated, you can always break them down to sub-custom Hooks. Extract the logic of your component to custom Hooks to make your code readable.
3. Use React Hooks Snippets
React Hooks Snippets is a Visual Studio Code extension to make React Hooks easier and faster. Currently, five hooks are supported:
useState()
useEffect()
useContext()
useCallback()
useMemo()
Other snippets have also been added. I have tried working with these Hooks and it has been one of the best practices Iâve personally used while working with them.
There are two ways you can add React Hooks snippets to your project:
Command Launch the VS Code Quick open (Ctrl+P), paste ext install ALDuncanson.react-hooks-snippets and press Enter.
Extension Marketplace Launch âVS Code Extension Marketplaceâ (Ctrl+Shift+X) and search for âReact Hook Snippetsâ. Then, look for the âAlduncansonâ icon.
I recommend the first snippet. Read more about the snippets here or check for the lastest Hooks snippets here.
4. Put Hooks Rules Into Consideration
Endeavor to always put the two rules of Hooks we learned earlier into consideration while working with React Hooks.
Only call your Hooks at the top level. Donât call Hooks inside loops, conditions or nested functions.
Always call Hooks from React function components or from custom Hooks, donât call Hooks from regular JavaScript functions.
The ESlint plugin called eslint-plugin-react-hooks enforces these two rules, you can add this plugin to your project if youâd like it as we explain above in rules of hooks section.
Best practices have not been fully resolved because Hooks are still relatively new. So adoption should be taken with precaution one would take in adopting in any early technology. With that in mind, Hooks are the way for the future of React.
Conclusion
I hope you enjoyed this tutorial. Weâve learned the two most important rules of React Hooks and how to effectively think in Hooks. We looked at functional components and some best practices in writing Hooks the right and effective way. As brief as the rules are, itâs important to make them your guiding compass when writing rules. If you are prone to forget it, you can make use of the ESLint plugin to enforce it.
I hope you will take all of the lessons learned here in your next React project. Good luck!
Resources
(ks, ra, yk, il)
Website Design & SEO Delray Beach by DBL07.co
Delray Beach SEO
source http://www.scpie.org/best-practices-with-react-hooks/ source https://scpie.tumblr.com/post/615588550236422144
0 notes
Text
Best Practices With React Hooks
About The Author
Adeneye David Abiodun is a JavaScript lover and a Tech Enthusiast, Founded @corperstechhub and currently a Lecturer / IT Technologist @critm_ugep. I build ⌠More about Adeneye âŚ
This article covers the rules of React Hooks and how to effectively start using them in your projects. Please note that in order to follow this article in detail, you will need to know how to use React Hooks.
React Hooks are a new addition in React 16.8 that let you use state and other React features without writing a class component. In other words, Hooks are functions that let you âhook intoâ React state and lifecycle features from function components. (They do not work inside class components.)
React provides a few built-in Hooks like useState. You can also create your own Hooks to reuse stateful behavior between different components. The example below shows a counter whose state is managed using the useState() hook. Each time you click on the button, we make use of setCount() to update the value of count by 1.
See the Pen [React Hook example with Counter](https://codepen.io/smashingmag/pen/QWbXMyM) by Adeneye Abiodun David.
See the Pen React Hook example with Counter by Adeneye Abiodun David.
This example renders a counter with a value of 0. When you click the button, it increments the value by 1. The initial value of the component is defined using useState.
const [count, setCount] = useState(0)
As you can see, we set that to be 0. Then we use the onClick() method to call setCount when we want to increment the value.
<button onClick={() => setCount(count + 1)}> Click me </button>
Before the release of React Hooks, this example would have used more lines of code, as weâd have had to make use of a class component.
Rules Of React Hooks
Before we dive deep into the best practices, we need to understand the rules of React Hooks which are also some of the fundamental concepts of the practices presented in this article.
React Hooks are JavaScript functions, but you need to follow two rules when using them.
Call Hooks at the top level;
Only call Hooks from React components.
Note: These two rules were introduced in React Hooks, as opposed to being part of JavaScript itself.
Letâs look at these rules in more detail.
Call Hooks At The Top Level
Donât call Hooks inside loops, conditions, or nested functions. Always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. Thatâs what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.
Letâs make a Form component which will have two states:
accountName
accountDetail
These states will have default values, weâll make use of the useEffect hook to persist the state to either the local storage of our browser or to the title of our document.
Now, this component will be maybe to successfully manage its state if it remains the same between multiple calls of useState and useEffect.
function Form() { // 1. Use the accountName state variable const [accountName, setAccountName] = useState('David'); // 2. Use an effect for persisting the form useEffect(function persistForm() { localStorage.setItem('formData', accountName); }); // 3. Use the accountDetail state variable const [accountDetail, setAccountDetail] = useState('Active'); // 4. Use an effect for updating the title useEffect(function updateStatus() { document.title = accountName + ' ' + accountDetail; }); // ... }
If the order of our Hooks changes (which can be possible when they are called in loops or conditionals), React will have a hard time figuring out how to preserve the state of our component.
// ------------ useState('David') // 1. Initialize the accountName state variable with 'David' useEffect(persistForm) // 2. Add an effect for persisting the form useState('Active') // 3. Initialize the accountdetail state variable with 'Active' useEffect(updateStatus) // 4. Add an effect for updating the status // ------------- // Second render // ------------- useState('David') // 1. Read the accountName state variable (argument is ignored) useEffect(persistForm) // 2. Replace the effect for persisting the form useState('Active') // 3. Read the accountDetail state variable (argument is ignored) useEffect(updateStatus) // 4. Replace the effect for updating the status // ...
Thatâs the order React follows to call our hooks. Since the order remains the same, it will be able to preserve the state of our component. But what happens if we put a Hook call inside a condition?
// đ´ We're breaking the first rule by using a Hook in a condition if (accountName !== '') { useEffect(function persistForm() { localStorage.setItem('formData', accountName); }); }
The accountName !== '' condition is true on the first render, so we run this Hook. However, on the next render the user might clear the form, making the condition false. Now that we skip this Hook during rendering, the order of the Hook calls becomes different:
useState('David') // 1. Read the accountName state variable (argument is ignored) // useEffect(persistForm) // đ´ This Hook was skipped! useState('Active') // đ´ 2 (but was 3). Fail to read the accountDetails state variable useEffect(updateStatus) // đ´ 3 (but was 4). Fail to replace the effect
React wouldnât know what to return for the second useState Hook call. React expected that the second Hook call in this component corresponds to the persistForm effect, just like during the previous render â but it doesnât anymore. From that point on, every next Hook call after the one we skipped would also shift by one â leading to bugs.
This is why Hooks must be called on the top level of our components. If we want to run an effect conditionally, we can put that condition inside our Hook.
Note: Check out the React Hook docs to read more on this topic.
Only Call Hooks From React Components
Donât call Hooks from regular JavaScript functions. Instead, you can call Hooks from React function components. Letâs take look at the difference between JavaScript function and React component below:
JavaScript Function
import { useState } = "react"; function toCelsius(fahrenheit) { const [name, setName] = useState("David"); return (5/9) * (fahrenheit-32); } document.getElementById("demo").innerHTML = toCelsius;
Here we import the useState hook from the React package, and then declared our function. But this is invalid as it is not a React component.
React Function
import React, { useState} from "react"; import ReactDOM from "react-dom"; function Account(props) { const [name, setName] = useState("David"); return <p>Hello, {name}! The price is <b>{props.total}</b> and the total amount is <b>{props.amount}</b></p> } ReactDom.render( <Account total={20} amount={5000} />, document.getElementById('root') );
Even though the body of both looks similar, the latter becomes a component when we import React into the file. This is what makes it possible for us to use things like JSX and React hooks inside.
If you happened to import your preferred hook without importing React (which makes it a regular function), you will not be able to make use of the Hook youâve imported as the Hook is accessible only in React component.
Call Hooks From Custom Hooks
A custom Hook is a JavaScript function whose name starts with use and that may call other Hooks. For example, useUserName is used below a custom Hook that calls the useState and useEffect hooks. It fetches data from an API, loops through the data, and calls setIsPresent() if the specific username it received is present in the API data.
export default function useUserName(userName) { const [isPresent, setIsPresent] = useState(false); useEffect(() => { const data = MockedApi.fetchData(); data.then((res) => { res.forEach((e) => { if (e.name === userName) { setIsPresent(true); } }); }); }); return isPresent; }
We can then go on to reuse the functionality of this hook in other places where we need such in our application. In such places, except when needed, we donât have to call useState or useEffect anymore.
By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code.
ESLint Plugin
ESLint plugin called eslint-plugin-react-hooks enforces the rules above. This comes in handy in enforcing the rules when working on a project. I suggest you make use of this plugin when working on your project, especially when working with others. You can add this plugin to your project if youâd like to try it:
// Your ESLint configuration { "plugins": [ // ... "react-hooks" ], "rules": { // ... "react-hooks/rules-of-hooks": "error", // Checks rules of Hooks "react-hooks/exhaustive-deps": "warn" // Checks effect dependencies } }
This plugin is included by default in Create React App. So you donât need to add it if you bootstrap your React applications using Create-React-App.
Thinking In Hooks
Letâs take a brief look at class components and functional components (with Hooks), before diving into the few Hooks best practices.
The simplest way to define a component in React is to write a JavaScript function that returns a React element:
function Welcome(props) { return <h1>Hello, {props.name}</h1>; }
The Welcome component accepts props which is an object that contains data and returns a React element. We can then import and render this component in another component.
The class component uses a programming methodology called Encapsulation which basically means that everything relevant to the class component will live within it. Life-cycle methods (constructors, componentDidMount(), render, and so on) give components a predictable structure.
Encapsulation is one of the fundamentals of OOP (Object-Oriented Programming). It refers to the bundling of data within the methods that operate on that data, and is used to hide the values or state of a structured data object inside a class â preventing unauthorized partiesâ direct access to them.
With Hooks, the composition of a component changes from being a combination of life-cycle Hooks â to functionalities with some render at the end.
Function Component
The example below shows how custom Hooks can be used in a functional component (without showcasing what the body is). However, what it does or can do is not limited. It could be instantiating state variables, consuming contexts, subscribing the component to various side effects â or all of the above if youâre using a custom hook!
function { useHook{...}; useHook{...}; useHook{...}; return ( ... ); }
Class Component
A class component requires you to extend from React.Component and create a render function which returns a React element. This requires more code but will also give you some benefits.
class { constructor(props) {...} componentDidMount() {...} componentWillUnmount() {...} render() {...} }
There are some benefits you get by using functional components in React:
It will get easier to separate container and presentational components because you need to think more about your componentâs state if you donât have access to setState() in your component.
Functional components are much easier to read and test because they are plain JavaScript functions without state or lifecycle-hooks.
You end up with less code.
The React team mentioned that there may be a performance boost for functional components in future React versions.
This leads to the first best practice when using React Hooks.
Hooks Best Practices
1. Simplify Your Hooks
Keeping React Hooks simple will give you the power to effectively control and manipulate what goes on in a component throughout its lifetime. Avoid writing custom Hooks as much as possible; you can inline a useState() or useEffect() instead of creating your own hook.
If you find yourself making use of a bunch of custom Hooks that are related in functionality, you can create a custom hook that acts as a wrapper for these. Letâs take a look at two different functional components with hooks below.
Functional Component v1
function { useHook(...); useHook(...); useHook(...); return( <div>...</div> ); }
Functional Component v2
function { useCustomHook(...); useHook(...); useHook(...); return( <div>...</div> ); }
v2 is a better version because it keeps the hook simple and all other useHooks are inline accordingly. This allows us to create functionality that can be reused across different components and also gives us more power to control and manipulate our components effectively. Instead of adopting v1 in which our components are littered with Hooks, you should make use of v2 which will make debugging easy and your code cleaner.
2. Organize And Structure Your Hooks
One of the advantages of React Hooks is the ability to write less code that is easy to read. In some cases, the amount of useEffect() and useState() can still be confusing. When you keep your component organized it will help in readability and keep the flow of your components consistent and predictable. If your custom Hooks are too complicated, you can always break them down to sub-custom Hooks. Extract the logic of your component to custom Hooks to make your code readable.
3. Use React Hooks Snippets
React Hooks Snippets is a Visual Studio Code extension to make React Hooks easier and faster. Currently, five hooks are supported:
useState()
useEffect()
useContext()
useCallback()
useMemo()
Other snippets have also been added. I have tried working with these Hooks and it has been one of the best practices Iâve personally used while working with them.
There are two ways you can add React Hooks snippets to your project:
Command Launch the VS Code Quick open (Ctrl+P), paste ext install ALDuncanson.react-hooks-snippets and press Enter.
Extension Marketplace Launch âVS Code Extension Marketplaceâ (Ctrl+Shift+X) and search for âReact Hook Snippetsâ. Then, look for the âAlduncansonâ icon.
I recommend the first snippet. Read more about the snippets here or check for the lastest Hooks snippets here.
4. Put Hooks Rules Into Consideration
Endeavor to always put the two rules of Hooks we learned earlier into consideration while working with React Hooks.
Only call your Hooks at the top level. Donât call Hooks inside loops, conditions or nested functions.
Always call Hooks from React function components or from custom Hooks, donât call Hooks from regular JavaScript functions.
The ESlint plugin called eslint-plugin-react-hooks enforces these two rules, you can add this plugin to your project if youâd like it as we explain above in rules of hooks section.
Best practices have not been fully resolved because Hooks are still relatively new. So adoption should be taken with precaution one would take in adopting in any early technology. With that in mind, Hooks are the way for the future of React.
Conclusion
I hope you enjoyed this tutorial. Weâve learned the two most important rules of React Hooks and how to effectively think in Hooks. We looked at functional components and some best practices in writing Hooks the right and effective way. As brief as the rules are, itâs important to make them your guiding compass when writing rules. If you are prone to forget it, you can make use of the ESLint plugin to enforce it.
I hope you will take all of the lessons learned here in your next React project. Good luck!
Resources
(ks, ra, yk, il)
Website Design & SEO Delray Beach by DBL07.co
Delray Beach SEO
source http://www.scpie.org/best-practices-with-react-hooks/ source https://scpie1.blogspot.com/2020/04/best-practices-with-react-hooks.html
0 notes
Text
Best Practices With React Hooks
About The Author
Adeneye David Abiodun is a JavaScript lover and a Tech Enthusiast, Founded @corperstechhub and currently a Lecturer / IT Technologist @critm_ugep. I build ⌠More about Adeneye âŚ
This article covers the rules of React Hooks and how to effectively start using them in your projects. Please note that in order to follow this article in detail, you will need to know how to use React Hooks.
React Hooks are a new addition in React 16.8 that let you use state and other React features without writing a class component. In other words, Hooks are functions that let you âhook intoâ React state and lifecycle features from function components. (They do not work inside class components.)
React provides a few built-in Hooks like useState. You can also create your own Hooks to reuse stateful behavior between different components. The example below shows a counter whose state is managed using the useState() hook. Each time you click on the button, we make use of setCount() to update the value of count by 1.
See the Pen [React Hook example with Counter](https://codepen.io/smashingmag/pen/QWbXMyM) by Adeneye Abiodun David.
See the Pen React Hook example with Counter by Adeneye Abiodun David.
This example renders a counter with a value of 0. When you click the button, it increments the value by 1. The initial value of the component is defined using useState.
const [count, setCount] = useState(0)
As you can see, we set that to be 0. Then we use the onClick() method to call setCount when we want to increment the value.
<button onClick={() => setCount(count + 1)}> Click me </button>
Before the release of React Hooks, this example would have used more lines of code, as weâd have had to make use of a class component.
Rules Of React Hooks
Before we dive deep into the best practices, we need to understand the rules of React Hooks which are also some of the fundamental concepts of the practices presented in this article.
React Hooks are JavaScript functions, but you need to follow two rules when using them.
Call Hooks at the top level;
Only call Hooks from React components.
Note: These two rules were introduced in React Hooks, as opposed to being part of JavaScript itself.
Letâs look at these rules in more detail.
Call Hooks At The Top Level
Donât call Hooks inside loops, conditions, or nested functions. Always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. Thatâs what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.
Letâs make a Form component which will have two states:
accountName
accountDetail
These states will have default values, weâll make use of the useEffect hook to persist the state to either the local storage of our browser or to the title of our document.
Now, this component will be maybe to successfully manage its state if it remains the same between multiple calls of useState and useEffect.
function Form() { // 1. Use the accountName state variable const [accountName, setAccountName] = useState('David'); // 2. Use an effect for persisting the form useEffect(function persistForm() { localStorage.setItem('formData', accountName); }); // 3. Use the accountDetail state variable const [accountDetail, setAccountDetail] = useState('Active'); // 4. Use an effect for updating the title useEffect(function updateStatus() { document.title = accountName + ' ' + accountDetail; }); // ... }
If the order of our Hooks changes (which can be possible when they are called in loops or conditionals), React will have a hard time figuring out how to preserve the state of our component.
// ------------ useState('David') // 1. Initialize the accountName state variable with 'David' useEffect(persistForm) // 2. Add an effect for persisting the form useState('Active') // 3. Initialize the accountdetail state variable with 'Active' useEffect(updateStatus) // 4. Add an effect for updating the status // ------------- // Second render // ------------- useState('David') // 1. Read the accountName state variable (argument is ignored) useEffect(persistForm) // 2. Replace the effect for persisting the form useState('Active') // 3. Read the accountDetail state variable (argument is ignored) useEffect(updateStatus) // 4. Replace the effect for updating the status // ...
Thatâs the order React follows to call our hooks. Since the order remains the same, it will be able to preserve the state of our component. But what happens if we put a Hook call inside a condition?
// đ´ We're breaking the first rule by using a Hook in a condition if (accountName !== '') { useEffect(function persistForm() { localStorage.setItem('formData', accountName); }); }
The accountName !== '' condition is true on the first render, so we run this Hook. However, on the next render the user might clear the form, making the condition false. Now that we skip this Hook during rendering, the order of the Hook calls becomes different:
useState('David') // 1. Read the accountName state variable (argument is ignored) // useEffect(persistForm) // đ´ This Hook was skipped! useState('Active') // đ´ 2 (but was 3). Fail to read the accountDetails state variable useEffect(updateStatus) // đ´ 3 (but was 4). Fail to replace the effect
React wouldnât know what to return for the second useState Hook call. React expected that the second Hook call in this component corresponds to the persistForm effect, just like during the previous render â but it doesnât anymore. From that point on, every next Hook call after the one we skipped would also shift by one â leading to bugs.
This is why Hooks must be called on the top level of our components. If we want to run an effect conditionally, we can put that condition inside our Hook.
Note: Check out the React Hook docs to read more on this topic.
Only Call Hooks From React Components
Donât call Hooks from regular JavaScript functions. Instead, you can call Hooks from React function components. Letâs take look at the difference between JavaScript function and React component below:
JavaScript Function
import { useState } = "react"; function toCelsius(fahrenheit) { const [name, setName] = useState("David"); return (5/9) * (fahrenheit-32); } document.getElementById("demo").innerHTML = toCelsius;
Here we import the useState hook from the React package, and then declared our function. But this is invalid as it is not a React component.
React Function
import React, { useState} from "react"; import ReactDOM from "react-dom"; function Account(props) { const [name, setName] = useState("David"); return <p>Hello, {name}! The price is <b>{props.total}</b> and the total amount is <b>{props.amount}</b></p> } ReactDom.render( <Account total={20} amount={5000} />, document.getElementById('root') );
Even though the body of both looks similar, the latter becomes a component when we import React into the file. This is what makes it possible for us to use things like JSX and React hooks inside.
If you happened to import your preferred hook without importing React (which makes it a regular function), you will not be able to make use of the Hook youâve imported as the Hook is accessible only in React component.
Call Hooks From Custom Hooks
A custom Hook is a JavaScript function whose name starts with use and that may call other Hooks. For example, useUserName is used below a custom Hook that calls the useState and useEffect hooks. It fetches data from an API, loops through the data, and calls setIsPresent() if the specific username it received is present in the API data.
export default function useUserName(userName) { const [isPresent, setIsPresent] = useState(false); useEffect(() => { const data = MockedApi.fetchData(); data.then((res) => { res.forEach((e) => { if (e.name === userName) { setIsPresent(true); } }); }); }); return isPresent; }
We can then go on to reuse the functionality of this hook in other places where we need such in our application. In such places, except when needed, we donât have to call useState or useEffect anymore.
By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code.
ESLint Plugin
ESLint plugin called eslint-plugin-react-hooks enforces the rules above. This comes in handy in enforcing the rules when working on a project. I suggest you make use of this plugin when working on your project, especially when working with others. You can add this plugin to your project if youâd like to try it:
// Your ESLint configuration { "plugins": [ // ... "react-hooks" ], "rules": { // ... "react-hooks/rules-of-hooks": "error", // Checks rules of Hooks "react-hooks/exhaustive-deps": "warn" // Checks effect dependencies } }
This plugin is included by default in Create React App. So you donât need to add it if you bootstrap your React applications using Create-React-App.
Thinking In Hooks
Letâs take a brief look at class components and functional components (with Hooks), before diving into the few Hooks best practices.
The simplest way to define a component in React is to write a JavaScript function that returns a React element:
function Welcome(props) { return <h1>Hello, {props.name}</h1>; }
The Welcome component accepts props which is an object that contains data and returns a React element. We can then import and render this component in another component.
The class component uses a programming methodology called Encapsulation which basically means that everything relevant to the class component will live within it. Life-cycle methods (constructors, componentDidMount(), render, and so on) give components a predictable structure.
Encapsulation is one of the fundamentals of OOP (Object-Oriented Programming). It refers to the bundling of data within the methods that operate on that data, and is used to hide the values or state of a structured data object inside a class â preventing unauthorized partiesâ direct access to them.
With Hooks, the composition of a component changes from being a combination of life-cycle Hooks â to functionalities with some render at the end.
Function Component
The example below shows how custom Hooks can be used in a functional component (without showcasing what the body is). However, what it does or can do is not limited. It could be instantiating state variables, consuming contexts, subscribing the component to various side effects â or all of the above if youâre using a custom hook!
function { useHook{...}; useHook{...}; useHook{...}; return (
...
); }
Class Component
A class component requires you to extend from React.Component and create a render function which returns a React element. This requires more code but will also give you some benefits.
class { constructor(props) {...} componentDidMount() {...} componentWillUnmount() {...} render() {...} }
There are some benefits you get by using functional components in React:
It will get easier to separate container and presentational components because you need to think more about your componentâs state if you donât have access to setState() in your component.
Functional components are much easier to read and test because they are plain JavaScript functions without state or lifecycle-hooks.
You end up with less code.
The React team mentioned that there may be a performance boost for functional components in future React versions.
This leads to the first best practice when using React Hooks.
Hooks Best Practices
1. Simplify Your Hooks
Keeping React Hooks simple will give you the power to effectively control and manipulate what goes on in a component throughout its lifetime. Avoid writing custom Hooks as much as possible; you can inline a useState() or useEffect() instead of creating your own hook.
If you find yourself making use of a bunch of custom Hooks that are related in functionality, you can create a custom hook that acts as a wrapper for these. Letâs take a look at two different functional components with hooks below.
Functional Component v1
function { useHook(...); useHook(...); useHook(...); return( <div>...</div> ); }
Functional Component v2
function { useCustomHook(...); useHook(...); useHook(...); return( <div>...</div> ); }
v2 is a better version because it keeps the hook simple and all other useHooks are inline accordingly. This allows us to create functionality that can be reused across different components and also gives us more power to control and manipulate our components effectively. Instead of adopting v1 in which our components are littered with Hooks, you should make use of v2 which will make debugging easy and your code cleaner.
2. Organize And Structure Your Hooks
One of the advantages of React Hooks is the ability to write less code that is easy to read. In some cases, the amount of useEffect() and useState() can still be confusing. When you keep your component organized it will help in readability and keep the flow of your components consistent and predictable. If your custom Hooks are too complicated, you can always break them down to sub-custom Hooks. Extract the logic of your component to custom Hooks to make your code readable.
3. Use React Hooks Snippets
React Hooks Snippets is a Visual Studio Code extension to make React Hooks easier and faster. Currently, five hooks are supported:
useState()
useEffect()
useContext()
useCallback()
useMemo()
Other snippets have also been added. I have tried working with these Hooks and it has been one of the best practices Iâve personally used while working with them.
There are two ways you can add React Hooks snippets to your project:
Command Launch the VS Code Quick open (Ctrl+P), paste ext install ALDuncanson.react-hooks-snippets and press Enter.
Extension Marketplace Launch âVS Code Extension Marketplaceâ (Ctrl+Shift+X) and search for âReact Hook Snippetsâ. Then, look for the âAlduncansonâ icon.
I recommend the first snippet. Read more about the snippets here or check for the lastest Hooks snippets here.
4. Put Hooks Rules Into Consideration
Endeavor to always put the two rules of Hooks we learned earlier into consideration while working with React Hooks.
Only call your Hooks at the top level. Donât call Hooks inside loops, conditions or nested functions.
Always call Hooks from React function components or from custom Hooks, donât call Hooks from regular JavaScript functions.
The ESlint plugin called eslint-plugin-react-hooks enforces these two rules, you can add this plugin to your project if youâd like it as we explain above in rules of hooks section.
Best practices have not been fully resolved because Hooks are still relatively new. So adoption should be taken with precaution one would take in adopting in any early technology. With that in mind, Hooks are the way for the future of React.
Conclusion
I hope you enjoyed this tutorial. Weâve learned the two most important rules of React Hooks and how to effectively think in Hooks. We looked at functional components and some best practices in writing Hooks the right and effective way. As brief as the rules are, itâs important to make them your guiding compass when writing rules. If you are prone to forget it, you can make use of the ESLint plugin to enforce it.
I hope you will take all of the lessons learned here in your next React project. Good luck!
Resources
(ks, ra, yk, il)
Website Design & SEO Delray Beach by DBL07.co
Delray Beach SEO
source http://www.scpie.org/best-practices-with-react-hooks/
0 notes