Sending GET, POST, PUT, DELETE Requests Using Axios In React

Hi, I’m Aya Bouchiha, today, we’ll cover sending POST and GET requests in react.js using axios.

Axios

axios: is a popular Javascript library used for making HTTP requests to an API.

docs

github

Why axios instead of fetch?…


This content originally appeared on DEV Community and was authored by Aya Bouchiha

Hi, I'm Aya Bouchiha, today, we'll cover sending POST and GET requests in react.js using axios.

Axios

axios: is a popular Javascript library used for making HTTP requests to an API.

Why axios instead of fetch?

I recommend reading this article by Faraz Kelhini :

Axios installation

cdn

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Or:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

npm

npm i axios

yarn

yarn add axios

bower

bower install axios

GET request using axios

GET: is a request used for getting or retrieving data or information from a specified server.

Code using then and catch

import { useEffect } from 'react';
import axios from 'axios';
const App = () => {
    useEffect(() => {
        const getTodo = () => {
            axios
                .get('https://jsonplaceholder.typicode.com/todos/1')
                .then((response) => {
                    console.log(response.status);
                    console.log(response.data);
                })
                .catch((e) => console.log('something went wrong :(', e));
        };
        getTodo();
    }, []);
    return <div>GET REQUEST</div>;
};
export default App;

Console

200
{userId: 1, id: 1, title: "delectus aut autem", completed: false}

Code using async and await

import { useEffect } from 'react';
import axios from 'axios';
const App = () => {
    useEffect(() => {
        const getTodo = async () => {
            try {
                const response = await axios.get(
                    'https://jsonplaceholder.typicode.com/todos/1',
                );
                console.log(response.status);
                console.log(response.data);
            } catch (e) {
                console.log('something went wrong :( ', e);
            }
        };
        getTodo();
    }, []);
    return <div>GET REQUEST</div>;
};
export default App;

Console

200
{userId: 1, id: 1, title: "delectus aut autem", completed: false}

POST request using axios

POST: is a request that is used for sending information or data to a specific server.

axios.post(url, data, config)

Code using then and catch

import { useEffect } from 'react';
import axios from 'axios';
const App = () => {
    useEffect(() => {
        const postTodo = () => {
            const data = {
                title: 'drink water',
                body: 'I should drink water',
                userId: 3,
            };
            const headers = { 'header-name': 'value' };
            const config = { headers, };
            axios
                .post(
                    'https://jsonplaceholder.typicode.com/posts',
                    data,
                    config,
                )
                .then((response) => {
                    console.log(response.status);
                    console.log(response.data);
                })
                .catch((e) => console.log('something went wrong :(', e));
        };
        postTodo();
    }, []);
    return <div>POST REQUEST</div>;
};
export default App;

console

201
{title: "drink water", body: "I should drink water", userId: 3, id: 101}

Code using async and await

import { useEffect } from "react";
import axios from "axios";
const App = () => {
  useEffect(() => {
    const postTodo = async () => {
      const data = {
        title: "drink water",
        body: "I should drink water",
        userId: 3
      };
      const headers = { "header-name": "value" };
      const config = { headers, };
      try {
        const response = await axios.post(
          "https://jsonplaceholder.typicode.com/posts",
          data,
          config
        );
        console.log(response.status);
        console.log(response.data);
      } catch (e) {
        console.log("something went wrong!",e);
      }
    };
    postTodo();
  }, []);
  return <div>POST REQUEST</div>;
};
export default App;

console

201
{title: "drink water", body: "I should drink water", userId: 3, id: 101}

PUT request using axios

PUT: is a request used for creating or updating a resource in a specific server.

Code using then and catch

import { useEffect } from 'react';
import axios from 'axios';

const todo = {
    id: 10,
    title: 'go to gym',
    body: 'practicing sport is very important',
    userId: 2,
};

const App = () => {
    useEffect(() => {
        axios
            .put('https://jsonplaceholder.typicode.com/posts/10', todo)
            .then((response) => {
                console.log(response.status);
                console.log(response.data);
            })
            .catch((e) => console.log('something went wrong :(', e));
    }, []);
    return <div>PUT REQUEST</div>;
};
export default App;

Console

200
{id: 10, title: "go to gym", body: "practicing sport is very important", userId: 2}

Code using async and await

import { useEffect } from 'react';
import axios from 'axios';

const todo = {
    id: 10,
    title: 'go to gym',
    body: 'practicing sport is very important',
    userId: 2,
};

const App = () => {
    useEffect(() => {
        const putTodo = async () => {
            try {
                const response = await axios.put(
                    'https://jsonplaceholder.typicode.com/posts/10',
                    todo,
                );
                console.log(response.status);
                console.log(response.data);
            } catch (e) {
                console.log('something went wrong :(', e);
            }
        };
        putTodo();
    }, []);
    return <div>PUT REQUEST</div>;
};
export default App;

Console

200
{id: 10, title: "go to gym", body: "practicing sport is very important", userId: 2}

DELETE request using axios

DELETE: is a request used to delete a specific resource in a server.

Code using then and catch

import { useEffect } from 'react';
import axios from 'axios';

const App = () => {
    useEffect(() => {
        axios
            .delete('https://jsonplaceholder.typicode.com/posts/10')
            .then((response) => {
                console.log(response.status);
            })
            .catch((e) => console.log('something went wrong!', e));
    }, []);
    return <div>DELETE REQUEST</div>;
};
export default App;

console

200

Code using async and await

import { useEffect } from 'react';
import axios from 'axios';

const App = () => {
    useEffect(() => {
        const deleteTodo = async () => {
            try {
                const response = await axios.delete(
                    'https://jsonplaceholder.typicode.com/posts/10',
                );
                console.log(response.status);
            } catch (e) {
                console.log('something went wrong!', e);
            }
        };
        deleteTodo();
    }, []);
    return <div>DELETE REQUEST</div>;
};
export default App;

console

200

Useful Resources

Suggested Posts

To Contact Me:

Happy coding!


This content originally appeared on DEV Community and was authored by Aya Bouchiha


Print Share Comment Cite Upload Translate Updates
APA

Aya Bouchiha | Sciencx (2021-09-03T08:58:43+00:00) Sending GET, POST, PUT, DELETE Requests Using Axios In React. Retrieved from https://www.scien.cx/2021/09/03/sending-get-post-put-delete-requests-using-axios-in-react/

MLA
" » Sending GET, POST, PUT, DELETE Requests Using Axios In React." Aya Bouchiha | Sciencx - Friday September 3, 2021, https://www.scien.cx/2021/09/03/sending-get-post-put-delete-requests-using-axios-in-react/
HARVARD
Aya Bouchiha | Sciencx Friday September 3, 2021 » Sending GET, POST, PUT, DELETE Requests Using Axios In React., viewed ,<https://www.scien.cx/2021/09/03/sending-get-post-put-delete-requests-using-axios-in-react/>
VANCOUVER
Aya Bouchiha | Sciencx - » Sending GET, POST, PUT, DELETE Requests Using Axios In React. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/09/03/sending-get-post-put-delete-requests-using-axios-in-react/
CHICAGO
" » Sending GET, POST, PUT, DELETE Requests Using Axios In React." Aya Bouchiha | Sciencx - Accessed . https://www.scien.cx/2021/09/03/sending-get-post-put-delete-requests-using-axios-in-react/
IEEE
" » Sending GET, POST, PUT, DELETE Requests Using Axios In React." Aya Bouchiha | Sciencx [Online]. Available: https://www.scien.cx/2021/09/03/sending-get-post-put-delete-requests-using-axios-in-react/. [Accessed: ]
rf:citation
» Sending GET, POST, PUT, DELETE Requests Using Axios In React | Aya Bouchiha | Sciencx | https://www.scien.cx/2021/09/03/sending-get-post-put-delete-requests-using-axios-in-react/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.