Home > database >  How to redirect to another page and display flash message in Nextjs
How to redirect to another page and display flash message in Nextjs

Time:12-08

I am working on Reactjs and nextjs,Right now i am submitting form via axios(Api) Form is submitting successfully but after submitting form i want page should change(should display Allblogs.js,something like redirect) and display flash message "Your form submitting successfully" How can we do this ? Here is my current code

const response = await axios({
              method: "post",
              url: "https://diggdevelopment.com/blackstallion_new/api/testinfo_new/",
              data: formData,
              headers: { "Content-Type": "multipart/form-data" },
                      }).then(function (response) {
                        alert('Form submitting successfully');
                        //should redirect and display flash messag on another page
                
            }).catch(function (error) {
               alert('respone is '  error);
            });

CodePudding user response:

You can push new path with query and in new page see if query exists so show the alert

    const router = useRouter();
const response = await axios({
              method: "post",
              url: "https://diggdevelopment.com/blackstallion_new/api/testinfo_new/",
              data: formData,
              headers: { "Content-Type": "multipart/form-data" },
                      }).then(function (response) {
                        router.push({ pathname: "/home", query: { form: "submited" } });
                
            })
             .catch(function (error) {
               alert('respone is '  error);
            });

and in home page :

const router = useRouter();

useEffect(() => {
 if(router.query?.form === 'submited')
  alert('Form submitting successfully');
}, [router.query]);

CodePudding user response:

If you're posting data to an external site and want to redirect back to your site, you could just add a "then" and redirect.

const router = useRouter();
const response = await axios({
              method: "post",
              url: "https://diggdevelopment.com/blackstallion_new/api/testinfo_new/",
              data: formData,
              headers: { "Content-Type": "multipart/form-data" },
                      }).then(function (response) {
                        alert('Form submitting successfully');
                        //should redirect and display flash messag on another page
                
            }).then(() => router.push('/home'))
    .catch(function (error) {
               alert('respone is '  error);
            });

If this is for an internal link, you can use forms and API routes.

  • Related