Home > Web Front-end > JS Tutorial > How to Use Axios in ReactJS - GET and POST Request

How to Use Axios in ReactJS - GET and POST Request

Susan Sarandon
Release: 2024-10-15 12:24:01
Original
1117 people have browsed it

Cara Penggunaan Axios di ReactJS - GET dan POST Request

How to Use Axios in ReactJS

Introduction

Axios is a popular library for performing HTTP requests such as GET, POST, PUT, DELETE, and others. Axios is very suitable for use in React applications because it provides easy syntax and supports Promises. This article will discuss how to use Axios in a ReactJS application.

Axios Installation
Make sure you have Axios installed in your React project:

npm install axios
Copy after login

Using Axios in React Components
For example, we want to retrieve data from an API using the GET method and display it in a React component.

  1. GET Request:
import React, { useEffect, useState } from 'react';
import axios from 'axios';

const App = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
        setData(response.data);
        setLoading(false);
      } catch (error) {
        setError(error);
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {data.map((post) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
};

export default App;

Copy after login

Explanation:

  • Use useEffect to call the fetchData function when the component is first loaded.
    • axios.get is used to retrieve data from the API URL.
    • State data, loading, and error is used to store retrieved data, loading state, and errors.

  1. POST Request: To send data to the server, you can use the POST method as follows:
import React, { useState } from 'react';
import axios from 'axios';

const App = () => {
  const [title, setTitle] = useState('');
  const [body, setBody] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const response = await axios.post('https://jsonplaceholder.typicode.com/posts', {
        title,
        body,
      });
      console.log('Response:', response.data);
      alert('Post successfully created!');
    } catch (error) {
      console.error('Error posting data:', error);
    }
  };

  return (
    <div>
      <h1>Create a Post</h1>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          placeholder="Title"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
        />
        <textarea
          placeholder="Body"
          value={body}
          onChange={(e) => setBody(e.target.value)}
        ></textarea>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
};

export default App;

Copy after login

Explanation:

  • The axios.post method is used to send title and body data to the API.
  • The handleSubmit function handles the form submission and sends data to the server.

The above is the detailed content of How to Use Axios in ReactJS - GET and POST Request. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template