Issue
I'm trying to add color by using the post method with axios in react. The backend side works very well. I can add a color, but I want an alert dialog to appear on the screen. if an error is encountered then show an error message when adding . Every time I press the button, it doesn't work, only if the axios operation is successful, the successful alert dialog will appear. If there is an error, the error alert dialgo should appear. I'm new to react so I dont know actually how to apply it my codes.
AddColor.js
import axios from "axios"
import { useState } from "react";
export default function AddColor() {
const [Name, setcolorName] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
axios({
method: 'post',
url: 'http://localhost:64082/api/color/add',
data: {
Name
}
})
}
return (
<div className="create">
<h2>Add a New Color</h2>
<form onSubmit={handleSubmit}>
<label>color Name:</label>
<input
type="text"
required
value={Name}
placeholder="please enter color name..."
onChange={(e) => setcolorName(e.target.value)}
/>
<button>Add Category</button>
</form>
</div>
)
}
Solution
I did a codesandbox.io to explain to you how to do it using async/await
syntax. I will paste the results here.
import { useState } from "react";
import axios from "axios";
export default function App() {
const [Name, setcolorName] = useState("");
const handleSubmit = async (e) => {
e.preventDefault();
try {
await axios({
method: "post",
url: "https://httpstat.us/200",
data: {
Name
}
});
return alert("Success!");
} catch (error) {
return alert("Error: " + error);
}
};
return ( ...
Answered By - Caio Gomes Answer Checked By - Marilyn (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.