After submitting the form using Add Button, I want the contents added to be displayed directly without refreshing the page url (NOT LOOKING FOR WINDOW.LOCATION.RELOAD). How do i make it work using ReactJS?
const formik = useFormik({
enableReinitialize: true,
initialValues: initialValue,
validationSchema: Yup.object().shape({
name: Yup.string().max(255),
}),
onSubmit: async (values, helpers) => {
try {
const url = `${protectedRes.apiHello.endpoint}/xyz/${params.Id}/list`;
getAccessToken(account, instance, inProgress)
.then((accessToken) => {
callPutApiWithToken(accessToken, url, productState).then((apiResponse) => {
console.log(apiResponse);
});
})
.catch((error) => {
console.log(error);
});
toast.success(`${t('Added')}`);
helpers.resetForm();
helpers.setStatus({ success: true });
helpers.setSubmitting(false);
onClose?.();
submitError = null;
} catch (err) {
console.error(err);
helpers.setStatus({ success: false });
helpers.setErrors({ submit: err.message });
submitError = err.message;
helpers.setSubmitting(false);
}
},
});
<Button
color="primary"
disabled={formik.isSubmitting}
onClick={(event) => {
formik.handleSubmit();
}}
variant="contained"
>
{`${t('Add')}`}
</Button>
how do I use e.preventDefault() method in this code?
CodePudding user response:
Add a custom event handler for the submit
-event.
function handleSubmit(event) {
event.preventDefault()
const text = new FormData(event.target).get("my_text")
console.log("text:", text)
// handle event manually
// axios.post(event)
document.querySelector("span").innerText = text
}
<form onsubmit="handleSubmit(event)">
<input type="text" placeholder="my_text" name="my_text">
<button type="submit">Submit</button>
</form>
<p>Your text: <span></span></p>
CodePudding user response:
When need to pass information to somewhere else, like a database, on submit requires a page refresh. To prevent this refresh, you can use the preventDefault() method in JavaScript within the function that is invoked on the form submission.
// Function that runs when submit button is pressed
handleSubmit(event){
// Prevents the default behavior that includes page refresh
event.preventDefault();
// Rest of the code
}
Read about this event https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
CodePudding user response:
If I understood properly, the solution doesn't necessarily lies in the React part of your system.
I think I understand well your problem: You have submitted a new entity, and after confirmation from the API you want to update the React UI with the newly-added entity.
Of course, there is no way to actually giving you React code for this since we don't know your page's component. Is it a table you want to update with the newly-added entity? Or is it maybe some list in card format? We don't know since you don't specify.
But let's rewind a bit: You need a proper API response before you can even think of updating your component/view/page/etc. with the new entity. Your API, upon successful addition of the entity, should respond with a copy of the added entity. Normally I create my REST API so that, on POST'ing of a new entity it responds with HTTP 201 CREATED
plus a copy of the entity in the body.
Once you have a well-behaved REST API as described above, you may read the response body, parse it and send this new entity to your React component. Generally speaking, after parsing you would add the new entity to an array (if we're talking a list component of some sort here) that is passed to said list component in props
.
I guess this is the best I can do for you right now.