1

I want to automatic redirect home page after click on update button, here is my handleSubmit code:

 const handleSubmit = (e) => {
    e.preventDefault();
    // access data from backend
    axios
      .put(`${process.env.REACT_APP_API}/post/${slug}`, {
        title,
        content,
        user,
      })
      .then((response) => {
        console.log(response);
        const { title, content, slug, user } = response.data;

        setState({ ...state, title, content, slug, user });
        alert(`Post Title ${response.data.title} is Updated`);
      })
      .catch((error) => {
        console.log(error.response);
      });
  };

Here I have use a alert when my post has been updated then show me, but now I need to redirect my home page. when I click on update button

Any suggestion please.

Alamin
  • 1,878
  • 1
  • 14
  • 34
  • Why use react and then reload? What is the point then? Or do you want to redirect TO the home page? – mplungjan Mar 03 '21 at 11:37
  • You're using React, so are you also using react-router? Or how did you set up your navigation? –  Mar 03 '21 at 11:40
  • 1
    If this is a React app, and you are using *react-router-dom* (or any other routing library), you can redirect using the routing library. For example: `Redirect` form *react-router-dom* or you can also do `history.push('/__path__')`. – Ajeet Shah Mar 03 '21 at 11:42
  • Ok, then should I do like this `import {Router} = require('react-router'); Router.push('/');` – Alamin Mar 03 '21 at 11:42
  • 1
    Do `history.push('/path_here')` – Ajeet Shah Mar 03 '21 at 11:44
  • 1
    Docs link: https://reactrouter.com/web/api/Hooks/usehistory –  Mar 03 '21 at 11:47
  • Also: the correct duplicate is: https://stackoverflow.com/questions/45089386/what-is-the-best-way-to-redirect-a-page-using-react-router –  Mar 03 '21 at 11:47

1 Answers1

1

You can use useHistory hook.

import { useHistory } from 'react-router-dom';

const Component = (props) => {
  const history = useHistory();
  const handleSubmit = (e) => {
    e.preventDefault();
    // access data from backend
    axios
      .put(`${process.env.REACT_APP_API}/post/${slug}`, {
        title,
        content,
        user,
      })
      .then((response) => {
        console.log(response);
        const { title, content, slug, user } = response.data;

        setState({ ...state, title, content, slug, user });
        alert(`Post Title ${response.data.title} is Updated`);
        // ********redirection here **********
        history.push("/");
        
      })
      .catch((error) => {
        console.log(error.response);
      });
  };
  
}
Akhil Chandran
  • 380
  • 3
  • 12