React JS CRUD – How to Insert Data Into Database Using API
In this tutorial, we will learn how to insert data into a database using an API in React JS. We will also implement a loader on form submit to provide a better user experience.
Step 1: Create a Form Component
First, let’s create a form component in React JS where users can input the data they want to insert into the database.
<form>
<input type="text" name="name" />
<input type="email" name="email" />
<button type="submit">Submit</button>
</form>
Step 2: Handle Form Submission
Next, we need to handle the form submission event and call the API to insert the data into the database. We can use the fetch
method to make a POST request to the API endpoint.
const handleSubmit = async (event) => {
event.preventDefault();
setLoading(true);
const formData = new FormData(event.target);
const data = {
name: formData.get('name'),
email: formData.get('email')
};
const response = await fetch('https://example-api.com/insertData', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
if(response.ok) {
alert('Data inserted successfully!');
} else {
alert('Error inserting data');
}
setLoading(false);
};
Step 3: Add Loader on Form Submit
To provide a better user experience, we can add a loader component that will be displayed while the form is being submitted.
{loading ? <div className="loader">Loading...</div> : null}
Conclusion
In this tutorial, we have learned how to insert data into a database using an API in React JS. We have also implemented a loader on form submit to improve the user experience. By following these steps, you can easily create a form in React JS and handle the submission of data to a database using an API.
This was so incredibly helpful, thank you!!
Please make admin and user login register logout authentication api while separating if admin go to dashboard and if user go to user porta.also implement with react js
Very nice video
Sir instead of making same video again n again can you please make videos on react redux with laravel backend
Brother make a full course video about Vue js with laravel
oh man this i was searching
Very important video