When uploading the form with react the states aren't getting updated like they update for a second then go back to the inputted values I don't know why is this happening
Gif showing the code behaivour
const [values, setValues] = useState({
// Single File upload hooks
singleFile: {},
selectSingleFile: false,
singleTitle: '',
singleArtist: '',
open: false,
// Multiple File upload hooks
multipleFiles: [],
selectMultipleFiles: false,
multipleTitle: '',
multipleArtist: '',
uploadStatus: Number,
});
const handleSubmit = (event) => {
// converting into the form object
const formData = new FormData();
formData.append('title', values.singleTitle);
formData.append('artist', values.singleArtist);
formData.append('file', values.singleFile);
// making request to the server
let reqOptions = {
url: '/music/singleFile',
method: 'POST',
data: formData,
};
axios.request(reqOptions).then(function (response) {
console.log(response);
setValues({ ...values, uploadStatus: response.status });
});
// Setting the hook back to default values
setValues({
...values,
singleFile: {},
selectSingleFile: false,
singleTitle: '',
singleArtist: '',
open: true,
});
event.preventDefault();
};
const handleSubmit = (event) => {
// converting into the form object
const formData = new FormData();
formData.append('title', values.singleTitle);
formData.append('artist', values.singleArtist);
formData.append('file', values.singleFile);
// making request to the server
let reqOptions = {
url: '/music/singleFile',
method: 'POST',
data: formData,
};
axios.request(reqOptions).then(function (response) {
console.log(response);
setValues({ ...values, uploadStatus: response.status });
}).then(res =>{
// Setting the hook back to default values
setValues({
...values,
singleFile: {},
selectSingleFile: false,
singleTitle: '',
singleArtist: '',
open: true,
});
});
event.preventDefault();
};
Place your state clear in a .then so then you know for sure it will only clear after the api call was succesful.