Salma mohamed
4 min readJun 11, 2023

Posting Data from Reactjs using axios.post()

Hello, please check the below code and we will try to understand it better

import React, {useState} from 'react'
import axios from 'axios'


function Example() {
const [input, setInput] = useState('');

const handleInputChange = (event) => {
setInput(event.target.value);
};

const handleSubmit = (event) => {
event.preventDefault();

const data = {
message: input
};

axios.post('/api/data', data)
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
};

return (
<div className='wrapper'>
<form onSubmit={handleSubmit}>
<input type="text" value={input} onChange={handleInputChange} />
<button type="submit">Submit</button>
</form>
</div>
)
}

export default Example;

First, let’s understand what is onChange?

This is a javascript method that is executed to allow you to perform certain actions or handle the event.

It is associated with an input element, such as a text field, checkbox, or dropdown list, and is triggered when the value of that input element changes.

For example, you might use the onChange method to

  1. update the state of your application,
  2. validate user input
  3. trigger other functions, or
  4. update the display based on the new input value.

Let’s see examples of the first 2 use cases for the onChange method:

//when we say update the state it means use the useState hook to update your 
//your state

import React, { useState } from 'react';

function MyComponent() {
const [inputValue, setInputValue] = useState('');

const handleChange = (event) => {
setInputValue(event.target.value);
};

return (
<div>
<input
type="text"
value={inputValue}
onChange={handleChange}
/>
<p>Current value: {inputValue}</p>
</div>
);
}

export default MyComponent;

Validating user input is an important task to ensure that the data entered by the user meets certain criteria or constraints. Here’s an example of how you can validate user input using the onChange event in React:

import React, { useState } from 'react';

function MyComponent() {
const [inputValue, setInputValue] = useState('');
const [error, setError] = useState('');

const handleChange = (event) => {
const value = event.target.value;
setInputValue(value);

// Perform validation
//below checks whether the characters user entered length is less than 6, if
//it does then the state for the error updates, else the state for the error
//stays empty " "

if (value.length < 6) {
setError('Input must be at least 6 characters long.');
} else {
setError('');
}
};

return (
<div>
<input
type="text"
value={inputValue}
onChange={handleChange}
/>
//bellow is a codition:
//says If error is truthy (i.e., it has a value),
// the error message is rendered; otherwise, nothing is rendered.
{error && <p>{error}</p>}
</div>
);
}

export default MyComponent;

Next…

onSumit: is an event associated with the <form> element, and the handleSubmit function is called when the form is submitted.

  • It takes the event object as a parameter, which represents the event that triggered the function.
  • By calling event.preventDefault(), the function prevents the default form submission behavior, which would cause the page to refresh.
  • You can access the form data by using the event.target.elements property, which provides access to the form elements by their name attribute.
  • Inside the handleSubmit function, you can perform form data validation, send the form data to a server, update the application state, or perform any other actions required for handling the form submission.

NB=> The handleSubmit function sends the form data to the server, the first general code we have in this post you see axios making a post request so that it posts/creates that data our form is receiving to our server.

Example:

//To perform form data validation
import React, { useState } from 'react';

function MyForm() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [error, setError] = useState('');

const handleSubmit = (event) => {
event.preventDefault();

// Perform form data validation
if (!name.trim()) {
setError('Please enter your name.');
return;
}

if (!email.trim()) {
setError('Please enter your email address.');
return;
}

// If form data is valid, submit the form
// ...
setError('');
console.log('Form submitted successfully');
};

return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Name:</label>
<input
type="text"
id="name"
value={name}
onChange={(event) => setName(event.target.value)}
/>
</div>
<div>
<label htmlFor="email">Email:</label>
<input
type="email"
id="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
/>
</div>
{error && <p>{error}</p>}
<button type="submit">Submit</button>
</form>
);
}

export default MyForm;

The handleSubmit function is called when the form is submitted. We prevent the default form submission behavior using event.preventDefault(). Then, we perform form data validation by checking if the name and email fields are empty or contain only whitespace. If any validation fails, we set the error state with the corresponding error message and return early to prevent form submission.

Next….

axios.post() This is a method provided by the Axios library, which is a popular JavaScript library used for making HTTP requests from a web browser or Node.js environment.

  • used for making POST requests to a specified URL
import axios from 'axios';

axios.post('https://api.example.com/post', { data: 'example data' })
.then(response => {
// Handle successful response
console.log(response.data);
})
.catch(error => {
// Handle error
console.error(error);
});

In this example, we import the Axios library and use the axios.post() method to send a POST request to the https://api.example.com/post URL. The second argument passed to axios.post() is the data that will be sent as the request body, in this case, an object with a data property.

The axios.post() method returns a promise, so we can chain .then() and .catch() methods to handle the response and error, respectively.

Inside the .then() callback, you can access the response data using response.data and perform any necessary actions based on the response from the server.

In the .catch() callback, any errors that occurred during the request or response handling can be caught and handled appropriately.

NOW TELL ME WHAT IS HARD IN THE MAIN CODE :)

import React, {useState} from 'react'
import axios from 'axios'

function Example() {
const [input, setInput] = useState('');

const handleInputChange = (event) => {
setInput(event.target.value);
};

const handleSubmit = (event) => {
event.preventDefault();

const data = {
message: input
};

axios.post('/api/data', data)
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
};

return (
<div className='wrapper'>
<form onSubmit={handleSubmit}>
<input type="text" value={input} onChange={handleInputChange} />
<button type="submit">Submit</button>
</form>
</div>
)
}

export default Example;
Salma mohamed
Salma mohamed

Written by Salma mohamed

software developer (Mern Stack)

No responses yet