Here's a clean template for both Axios
and fetch
covering the 4 major HTTP methods: GET, POST, PUT, and
🔧 Axios Template (with async/await
)
import axios from 'axios';
const API_URL = 'https://jsonplaceholder.typicode.com/todos';
// ✅ GET
export const getTodos = async () => {
try {
const response = await axios.get(API_URL);
return response.data;
} catch (error) {
console.error("GET error:", error);
}
};
// ✅ POST
export const createTodo = async (newTodo) => {
try {
const response = await axios.post(API_URL, newTodo);
return response.data;
} catch (error) {
console.error("POST error:", error);
}
};
// ✅ PUT (full update)
export const updateTodo = async (id, updatedTodo) => {
try {
const response = await axios.put(`${API_URL}/${id}`, updatedTodo);
return response.data;
} catch (error) {
console.error("PUT error:", error);
}
};
// ✅ DELETE
export const deleteTodo = async (id) => {
try {
const response = await axios.delete(`${API_URL}/${id}`);
return response.data;
} catch (error) {
console.error("DELETE error:", error);
}
};
🛠️ Fetch Template (with async/await
)
const API_URL = 'https://jsonplaceholder.typicode.com/todos';
// ✅ GET
export const getTodos = async () => {
try {
const response = await fetch(API_URL);
return await response.json();
} catch (error) {
console.error("GET error:", error);
}
};
// ✅ POST
export const createTodo = async (newTodo) => {
try {
const response = await fetch(API_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newTodo)
});
return await response.json();
} catch (error) {
console.error("POST error:", error);
}
};
// ✅ PUT
export const updateTodo = async (id, updatedTodo) => {
try {
const response = await fetch(`${API_URL}/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(updatedTodo)
});
return await response.json();
} catch (error) {
console.error("PUT error:", error);
}
};
// ✅ DELETE
export const deleteTodo = async (id) => {
try {
const response = await fetch(`${API_URL}/${id}`, {
method: 'DELETE'
});
return await response.json();
} catch (error) {
console.error("DELETE error:", error);
}
};