Playing Around with Axios for CRUD
Setting Up Your React App
npm create vite@latest axios-crud --template react
cd axios-crud
npm install axiosCreating the Backend API
Basic CRUD Operations with Axios
1. Create (POST)
import React, { useState } from 'react';
import axios from 'axios';
const CreatePost = () => {
const [title, setTitle] = useState('');
const [body, setBody] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
const post = { title, body };
try {
const response = await axios.post('https://jsonplaceholder.typicode.com/posts', post);
console.log(response.data);
} catch (error) {
console.error('There was an error creating the post!', error);
}
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>Title:</label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
</div>
<div>
<label>Body:</label>
<textarea
value={body}
onChange={(e) => setBody(e.target.value)}
/>
</div>
<button type="submit">Create Post</button>
</form>
);
};
export default CreatePost;2. Read (GET)
3. Update (PUT)
4. Delete (DELETE)
Bringing It All Together
Conclusion
Last updated