Reference
https://axios-http.com/docs/intro
Terminology
- Endpoint
- Request to an endpoint
// Advanced use of Axios
import axios from "axios";
import React from "react";
const baseURL = "https://jsonplaceholder.typicode.com/posts/1";
export default function App() {
const [post, setPost] = React.useState(null);
React.useEffect(async() => {
try {
setError('')
setLoading(true)
const response = await axios.get(baseURL)
setPost(response.data);
} catch (err) {
setError(err.message)
} finally {
setLoading(false)
}
}, []);
if (!post) return null;
return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
);
}
Introduction to Axios
- Make XMLHttpRequests from the browser
- Make http requests from node.js
- Supports the Promise API
- Intercept request and response
- Transform request and response data
- Cancel requests
- Timeouts
- Query parameters serialization with support for nested entries
- Automatic request body serialization to:
- JSON (
application/json
) - Multipart / FormData (
multipart/form-data
) - URL encoded form (
application/x-www-form-urlencoded
)
- JSON (
- Posting HTML forms as JSON
- Automatic JSON data handling in response
- Progress capturing for browsers and node.js with extra info (speed rate, remaining time)
- Setting bandwidth limits for node.js
- Compatible with spec-compliant FormData and Blob (including
node.js
) - Client side support for protecting against XSRF
Installation
npm i axios
Examples of use of Axios
GET /posts/1
Get a single post from the /posts endpoint
import axios from "axios";
import React from "react";
const baseURL = "https://jsonplaceholder.typicode.com/posts/1";
export default function App() {
const [post, setPost] = React.useState(null);
React.useEffect(() => {
axios.get(baseURL).then((response) => {
setPost(response.data);
});
}, []);
if (!post) return null;
return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
);
}
POST /posts
Create a new 'post' by POSTing the data in the body.
import axios from "axios";
import React from "react";
const baseURL = "https://jsonplaceholder.typicode.com/posts";
export default function App() {
const [post, setPost] = React.useState(null);
React.useEffect(() => {
axios.get(`${baseURL}/1`).then((response) => {
setPost(response.data);
});
}, []);
function createPost() {
axios
.post(baseURL, {
title: "Hello World!",
body: "This is a new post."
})
.then((response) => {
setPost(response.data);
});
}
if (!post) return "No post!"
return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
<button onClick={createPost}>Create Post</button>
</div>
);
}
PUT /posts/1
Update a given resource using a PUT request.
import axios from "axios";
import React from "react";
const baseURL = "https://jsonplaceholder.typicode.com/posts";
export default function App() {
const [post, setPost] = React.useState(null);
React.useEffect(() => {
axios.get(`${baseURL}/1`).then((response) => {
setPost(response.data);
});
}, []);
function updatePost() {
axios
.put(`${baseURL}/1`, {
title: "Hello World!",
body: "This is an updated post."
})
.then((response) => {
setPost(response.data);
});
}
if (!post) return "No post!"
return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
<button onClick={updatePost}>Update Post</button>
</div>
);
}
DELETE posts/1
import axios from "axios";
import React from "react";
const baseURL = "https://jsonplaceholder.typicode.com/posts";
export default function App() {
const [post, setPost] = React.useState(null);
React.useEffect(() => {
axios.get(`${baseURL}/1`).then((response) => {
setPost(response.data);
});
}, []);
function deletePost() {
axios
.delete(`${baseURL}/1`)
.then(() => {
alert("Post deleted!");
setPost(null)
});
}
if (!post) return "No post!"
return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
<button onClick={deletePost}>Delete Post</button>
</div>
);
}
Catching Errors
GET /posts/badendpoint
This endpoint does not exist and will return a 404 status code.
import axios from "axios";
import React from "react";
const baseURL = "https://jsonplaceholder.typicode.com/posts";
export default function App() {
const [post, setPost] = React.useState(null);
const [error, setError] = React.useState(null);
React.useEffect(() => {
// invalid url will trigger an 404 error
axios.get(`${baseURL}/asdf`).then((response) => {
setPost(response.data);
}).catch(error => {
setError(error);
});
}, []);
if (error) return `Error: ${error.message}`;
if (!post) return "No post!"
return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
);
}
GOOD POINTS
You can tell Axios to remember the baseURL
import axios from "axios";
import React from "react";
const client = axios.create({
baseURL: "https://jsonplaceholder.typicode.com/posts"
});
export default function App() {
const [post, setPost] = React.useState(null);
React.useEffect(() => {
client.get("/1").then((response) => {
setPost(response.data);
});
}, []);
function deletePost() {
client
.delete("/1")
.then(() => {
alert("Post deleted!");
setPost(null)
});
}
if (!post) return "No post!"
return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
<button onClick={deletePost}>Delete Post</button>
</div>
);
}
Async - Await syntax
import axios from "axios";
import React from "react";
const client = axios.create({
baseURL: "https://jsonplaceholder.typicode.com/posts"
});
export default function App() {
const [post, setPost] = React.useState(null);
React.useEffect(() => {
async function getPost() {
const response = await client.get("/1");
setPost(response.data);
}
getPost();
}, []);
async function deletePost() {
await client.delete("/1");
alert("Post deleted!");
setPost(null);
}
if (!post) return "No post!"
return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
<button onClick={deletePost}>Delete Post</button>
</div>
);
}