This is a memo when I compare these two methods.
1.GET
fetch
fetch(url)
.then((res) => {
if (!res.ok) {
// need error handling here
throw Error();
}
// need conversion
return res.json();
})
.then((data) => {
// use this data
})
.catch((error) => // error handling )
.finally(() => // this is optional);
axios
You can omit .get when using GET method
axios.get(url)
.then((response) => {
const data = response.data;
// use this data directly
})
.catch((error) => // error handling)
.finally(() => // this is optional);
2. POST
fetch
fetch(url,
{
method: "POST",
// you can omit headers nowadays
headers: {
"Content-Type": "application/json",
},
// need conversion
body: JSON.stringify(
{
tag: data.tag,
imageUrl: url,
})
})
.then((res) => {
// need error handling here
if (!res.ok) {
throw Error();
}
})
.catch((error) => { // error handling });
axios
axios.post(url,
{
// you can put an object directly
tag: data.tag,
imageUrl: url,
})
.then((res) => { // success operations})
.catch((error) => { // error handling });
3. DELETE
fetch
fetch(url,
{
method: "DELETE",
})
.then((res) => {
// need error handling here
if (!res.ok) {
throw Error();
}
// success operation
})
.catch((error) => { // error handling })
axios
axios.delete(url)
.then((*res*) => {
// success operation
})
.catch((error) => setError("Delete failed"))
.finally(() => setLoading(false));
conclusion
I finally understand why a lot of developers prefer to use axios even though we need to do a cumbersome process of installing and importing. It is obvious that axios is much simpler than fetch, and we can avoid unconscious bugs because of forgetting throwing errors. Therefore, I will use axios from now on.
Thank you for reading.
I’m happy if you give me some comments advice or feedback :)
The original article is here
Top comments (0)