Search code examples
javascriptreactjsreact-router-dombrowser-historyreact-functional-component

Why does my history.push work in one function but the other?


Problem: I have been trying to use props.history.push on my Edit function. I previously used it on my add function and it worked. I have the same imports and the only main difference is that I am also using useEffect in my Edit function while in my add function I only have useState. And also the fact I need to access each id in edit.

Error: TypeError: Cannot read property 'history' of undefined

Attempts: I have currently tried using Redirect which just redirected without applying changes. Also using history.push works within the button onClick but it does not apply my changes. Another solution I have seen often is let history=useHistory() after importing useHistory() but that gives me a hook error which I assumed it may be a version issue. However, my other main concern is that why does it work on my Add() function.

Add.js click Handler:

function handleSubmit(e) {
  e.preventDefault();
  axios({
    method: "post",
    url: "http://localhost:5000/add",
    data: body,
  })
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });
  console.log(state);
  props.history.push("/list");
}

This works perfectly.

Edit:

function handleSubmit(e, props) {
  e.preventDefault();
  axios({
    method: "put",
    url: "http://localhost:5000/update-list/" + testid,
    data: body,
  })
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });
  console.log(state);
  props.history.push('/list');
}

function handleChange(e, field) {
  e.preventDefault();
  setState({
    ...state,
    [field]: e.target.value,
  });
}

The rest of the code is also almost the same aside from using useEffect so I could give default values to the fields. This has been really confusing me. Any help would be appreciated. And let me know if you needed more details!


Solution

  • I was passing the props in the handler instead of the Edit function itself, and that is why it did not work. So the code should be:

    function handleSubmit(e) {
        e.preventDefault();
        axios({
          method: "put",
          url: "http://localhost:5000/update-list/" + testid,
          data: body,
        })
          .then(function (response) {
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });
        console.log(state);
        props.history.push('/list');
      }
    

    That fixed my issue and now it works! I'm surprised I did not notice this earlier as it took me ages to figure this out.