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
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.
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;
Explanation:
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;
Explanation:
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!