DEV Community

Cover image for How To Post Data In React JS Using Axios
Udemezue John
Udemezue John

Posted on

How To Post Data In React JS Using Axios

Introduction.

When building React applications, handling data flow between your frontend and backend is essential. One of the most common tasks you’ll face is sending data to an API.

Axios, a promise-based HTTP client, makes this process much simpler. So, if you’re looking to learn how to post data in React using Axios, you’re in the right place. Let me walk you through it!

What Is Axios?

Before diving into how to use Axios in React, it's important to understand what Axios is.

Axios is a popular JavaScript library that simplifies making HTTP requests to external resources like APIs.

It works both on the client and server-side and supports features like:

  • Automatic JSON data transformation: Axios automatically converts your JavaScript objects into JSON format.
  • Interceptors: You can define middleware for requests or responses, making error handling more manageable.
  • Cross-browser support: It works on older browsers as well.

In short, Axios is an easy way to handle requests like GET, POST, PUT, and DELETE, and it’s particularly useful in React applications where you often work with APIs.

How Do I Install Axios in React?

Before posting data using Axios, the first thing you'll need is to install Axios in your React project. Here's how you can do that:

npm install axios
Enter fullscreen mode Exit fullscreen mode

Or, if you’re using Yarn:

yarn add axios
Enter fullscreen mode Exit fullscreen mode

Once it's installed, you can start using Axios to make HTTP requests in your components.

How Do I Post Data in React Using Axios?

Let’s break down the steps to post data using Axios in React.

1. Setting Up the React Component.

First, create a form in your React component that will capture the data you want to send to the API. Here’s an example of a simple form for submitting user information:

import React, { useState } from "react";
import axios from "axios";

function PostForm() {
  const [user, setUser] = useState({
    name: "",
    email: "",
    password: ""
  });

  const handleChange = (e) => {
    setUser({
      ...user,
      [e.target.name]: e.target.value,
    });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    axios
      .post("https://example.com/api/users", user)
      .then((response) => {
        console.log("Data posted successfully:", response.data);
      })
      .catch((error) => {
        console.error("Error posting data:", error);
      });
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        name="name"
        value={user.name}
        onChange={handleChange}
        placeholder="Name"
      />
      <input
        type="email"
        name="email"
        value={user.email}
        onChange={handleChange}
        placeholder="Email"
      />
      <input
        type="password"
        name="password"
        value={user.password}
        onChange={handleChange}
        placeholder="Password"
      />
      <button type="submit">Submit</button>
    </form>
  );
}

export default PostForm;

Enter fullscreen mode Exit fullscreen mode

2. Handling Form Submission.

When a user fills out this form and hits "Submit," the handleSubmit function gets triggered. Here's how the code works:

  • Event Handling: When a user types in the form, the handleChange method updates the state with the user input.
  • Posting Data: Once the form is submitted, Axios sends a POST request to the API using the axios.post method. The user object contains the form data, and Axios sends it in JSON format.

This simple form now successfully posts data using Axios when the submit button is clicked.

3. Error Handling.

Axios makes error handling a breeze. You can catch errors by using .catch() in your request, as shown above.

Additionally, Axios supports request interceptors, which allow you to handle errors globally for all requests.

Here's a more comprehensive way to handle both the success and error cases:

axios
  .post("https://example.com/api/users", user)
  .then((response) => {
    alert("User successfully created!");
  })
  .catch((error) => {
    if (error.response) {
      // The server responded with a status code other than 2xx
      console.error("Error response:", error.response.data);
    } else if (error.request) {
      // The request was made but no response was received
      console.error("No response received:", error.request);
    } else {
      // Something else happened
      console.error("Error", error.message);
    }
  });

Enter fullscreen mode Exit fullscreen mode

This code handles different error cases, ensuring a more user-friendly experience.

4. Async/Await Syntax.

If you prefer async/await, Axios works well with it. Here’s how you can refactor the handleSubmit function to use async/await:

const handleSubmit = async (e) => {
  e.preventDefault();
  try {
    const response = await axios.post("https://example.com/api/users", user);
    console.log("Data posted successfully:", response.data);
  } catch (error) {
    console.error("Error posting data:", error);
  }
};
Enter fullscreen mode Exit fullscreen mode

Using async/await often makes the code more readable and easier to manage when dealing with multiple asynchronous requests.

Pros and Cons of Using Axios in React

Pros:

  • Simplified HTTP Requests: Axios abstracts away much of the complexity involved in making HTTP requests, making the code cleaner and more manageable.
  • Automatic JSON Parsing: Axios automatically converts data to JSON, which saves time and reduces the likelihood of errors.
  • Wide Browser Support: Axios works across older browsers and provides better error handling than the built-in fetch API.
  • Interceptors: You can define request and response interceptors globally, allowing for consistent error handling or token injection across all requests.

Cons:

  • Slightly Larger Size: Axios is larger than the built-in fetch API. While the difference is minor, it might matter in applications where performance and bundle size are critical.
  • No Native Streaming: Axios does not natively support request or response streaming. If your application needs that, fetch might be a better choice.
  • Dependencies: Adding a third-party library like Axios introduces another dependency to maintain in your project.

Conclusion.

Posting data in React using Axios is an efficient way to handle form submissions, user data, or any API interaction.

Axios simplifies both the process and error handling, making it a solid choice over the native fetch API for most applications.

If you need to send complex data structures or handle authentication tokens, Axios provides a lot of flexibility out of the box.

Now, have you tried posting data with Axios in your projects yet, or are you still using the native fetch API?

Top comments (0)