0

I am trying to add redirect functionality to my app when a form has been submitted, but when I try it I get the error cannot read property props of undefined

my submit function is as follows

  const handleSubmit = e => {
    e.preventDefault();
const authtoken = getCookie('token');
    if (name && email && tel && dob) {
        setFormData({ ...formData, textChange: 'Submitting' });
        axios
      .post(`${process.env.REACT_APP_API_URL}/user/new`,
        {
                name,
                email,
                tel,
                dob
        },
        {
          headers: {
            Authorization: `Bearer ${authtoken}`
          }
        }
      )
          .then(res => {
            setFormData({
              ...formData,
              name: '',
              email: '',
              tel: '',
              dob: '',
              textChange: 'Submitted'
            });

            toast.success(res.data.message);
            this.props.history.push('/next');
          })
          .catch(err => {
            setFormData({
              ...formData,
              name: '',
              email: '',
              tel: '',
              dob: '',
              textChange: 'Submit'
            });
            toast.error('Something went wrong with the submission');
          });
      
    } else {
      toast.error('Please fill all fields');
    }
  };

it works fine if I remove

  this.props.history.push('/next');

but it is used to redirect after the submission

what have I done wrong here and how can I fix it

or is there a different way to redirect after a submission

Thanks in advance

nad34
  • 343
  • 4
  • 13
  • Does this answer your question? [How to push to History in React Router v4?](https://stackoverflow.com/questions/42701129/how-to-push-to-history-in-react-router-v4) – Marsroverr Jul 13 '21 at 15:34
  • have you tried wrapping your module export with `withRouter`? something like : `export default withRouter(MyComponent)`, where `import {withRouter} from 'react-router-dom` – punjira Jul 13 '21 at 15:44
  • and the error log `cannot read property props of undefined` suggests that your inside a functional component. try removing `this` keyword – punjira Jul 13 '21 at 15:46
  • I have tried it with the `withRouter` thing and it did not work and if I remove this from this.props.history.push I get an error that `props` is not defined – nad34 Jul 13 '21 at 15:54
  • If you're using a functional component (let's say the name is `App`), then you need to define props by passing `props` as an argument. i.e., `App = (props) => {... ` – Areeb Khan Jul 13 '21 at 16:07

0 Answers0