DEV Community

Cover image for Using Axios with React
Mrityunjay-Palled
Mrityunjay-Palled

Posted on

Using Axios with React

Axios is an HTTP-based client for node.js and browsers that allows you to make requests to a given endpoint.

Setting up Axios with React:

You can run the following command to install Axios in your current React environment .

npm install axios
Enter fullscreen mode Exit fullscreen mode

Making a GET request:

import React, { useEffect, useState } from 'react'
import axios from 'axios'

const App = () => {
  const [allPosts,setAllPosts]=useState([])
  useEffect(()=>{
    getAllPosts()
  },[])

  const getAllPosts=()=>{
    axios.get("https://jsonplaceholder.typicode.com/posts")
    .then((posts)=>{
      setAllPosts(posts.data)
    })
  }

  return (
    <>
     {allPosts?.map((post)=>(
      <li key={post.id}>{post.title}</li>
     ))}
    </>
  )
}

export default App

Enter fullscreen mode Exit fullscreen mode

As we see above, we are using Axios to make GET requests to the server. We are passing a URL as a parameter to the get method provided by Axios. Since we know Axios is promise-based, we are using the ".then" callback to get all the posts that are returned by the server. We are using useEffect to invoke the getAllPosts function whenever the component mounts.

Making a POST request:

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

const App = () => {
  const [postAdded, setPostAdded] = useState(false);
  const addMyNewPost = () => {
    let _newPost = {
      userId: 1,
      title: "Hello People.....!!!",
      body: "Have a Great Day...!!!",
    };
    axios
      .post("https://jsonplaceholder.typicode.com/posts", _newPost)
      .then((post) => {
        if (post) setPostAdded(true);
      });
  };

  return (
    <>
      <button onClick={addMyNewPost}>Add My New Post</button>
      {postAdded ? <p>New Post Added</p> : null}
    </>
  );
};

export default App;


Enter fullscreen mode Exit fullscreen mode

As we see above, unlike the get method, we are also passing data that needs to be posted on the server along with the URL.In our case, the data payload that needs to be posted on the server is stored in "_newPost". Whenever a user clicks on the button, the addMyNewPost function will be triggered, which then triggers the POST API call.The request payload and the response are as shown below.

Image description

Image description

since we are using the JSON Placeholder API. The resources will not really be updated on the server, but they are faked as if they were. As we see above we are getting proper response from the server for our POST request. In this way we can post data to the server using Axios.

Error handling:

To handle errors we can make use of ".catch" block.Inside the block we can use the error object returned by the axios to handle the subsequent errors

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

const App = () => {
  const [allPosts, setAllPosts] = useState([]);

  useEffect(() => {
    getAllPosts();
  }, []);

  const getAllPosts = () => {
    axios
      .get("https://jsonplaceholder.typicode.com/posts")
      .then((posts) => {
        setAllPosts(posts.data);
      })
      .catch((error) => {
        if (error.response) {
          // The request was made and the server responded with a status code
          console.log(error.response.data);
          console.log(error.response.status);
          console.log(error.response.headers);
        } else if (error.request) {
          // The request was made but no response was received
          console.log(error.request);
        } else {
          // Something happened in setting up the request that triggered an Error
          console.log("Error", error.message);
        }
      });
  };

  return (
    <>
      {allPosts?.map((post) => (
        <li key={post.id}>{post.title}</li>
      ))}
    </>
  );
};

export default App;


Enter fullscreen mode Exit fullscreen mode

Top comments (0)