how to use in Reactjs functional component history.push
Asked Answered
A

4

19

I have a functional component that has form. Onsubmit call I would like to redirect to another page.

function ProfileForm(props) {
 // many code removed
 const onSubmit = (data, e) => {
   e.target.reset();
   history.push({
  pathname:  "/OnSubmit",
  state: {
    response: messageFromServer 
   } 
  }
}
// many code removed
}

I got this erro:-

Unexpected use of 'history' no-restricted-globals

After Googling the error I found a similar kind of answer for location. Answer was: Try adding window before location (i.e. window.location). So I tried:-

  window.history.push({
  pathname:  "/OnSubmit",
  state: {
    response: messageFromServer 
  } 
}

got new error:-

Unhandled Rejection (TypeError): window.history.push is not a function

Ancelin answered 3/3, 2020 at 22:13 Comment(1)
Try window.history.pushState().Uncourtly
B
42

I think you handle routing with react-router. If so, you need to use the history object which is passed through the ReactRouterContext. To do that, you need to use useHistory hook to get the history object.

// ...
import { useHistory } from "react-router";
// ...


function ProfileForm(props) {
  const history = useHistory();
  const onSubmit = (data, e) => {
     e.target.reset();
     history.push({
        pathname:  "/OnSubmit",
        state: {
          response: messageFromServer 
        } 
     });
  }
}
Butta answered 3/3, 2020 at 22:24 Comment(7)
yes, it works. But there is another problem. Before this call I make a post request as: axios.post('http://localhost:8080/profile', profile) .then(res => { setMessageFromServer(res.data) }).catch((error) => { // handle this error setMessageFromServer(error.data) }) I would like to get this response and send to the OnSubmit page. How can i wait for this response?Ancelin
It's a little bit hard to recommend something without knowing your routing and state management architecture. You can lift the state to the first mutual parent of ProfileForm and OnSubmitPage, pass a callback prop to ProfileForm called onSuccess, and use it like, axios.post('http://localhost:8080/profile', profile).then(res => { onSuccess(res.data); history.push("/onSubmit"); }).... Then, the mutual parent can pass this state to OnSubmitPage.Obsolete
If you are using redux or mobx, that's a whole another story and lots of different solutions. You can use contextAPI. You can even simply write the data so sessionStorage, redirect to OnSubmitPage and read the value from the storage. It al depends on your architecture.Obsolete
Handling API responses is a big topic in React. There are simple ways, advanced ways and "hardly maintainable" ways. You can use redux or mobx but some of the community is recently running away from them because of the complexity and their negative impacts. There are also people trying to separate the UI state from the API state. They say that the UI state like isDarkTheme, isDrawerOpen should be stored to a separate store from the which holds the responses of an API (this simply becomes a cache). You can check swr and react-query too. Like I said. Lots of alternatives.Obsolete
I'm not using redux or mobx. I just need to wait until I get response from the server. I will try to follow ur callback solution.Ancelin
Thanks that call back worked fine. How do I prevent the user to go back after he submitted? I meant when he is on OnSubmit page, he can't go back to ProfileForm or even if he goes back there won't be any old data. It should be an empty form.Ancelin
if you are using react-router-dom v5, then you should import from react-router-dom: import { useHistory } from "react-router-dom";Cenobite
P
4

Instead of history.push try to use navigate

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

const addToCartHandler = () => {
  navigate(`/cart/${productId}?qty=${qty}`)
};
Propst answered 4/2, 2022 at 5:42 Comment(1)
Nowadays this should be the accepted answer. useNavigate is a more recent hook and it makes your code more intuitive.Lefton
A
1

Use props.history Instead

const onSubmit = (data, e) => {
   e.target.reset();
   props.history.push("/OnSubmit")
  }
}
Adversity answered 12/10, 2022 at 15:52 Comment(0)
A
0

You can use useHistory(). The follwoing code can help you.

import { useHistory } from "react-router";

export default function Checkout(props) {
    
const history = useHistory();
 
return (
              <React.Fragment>
                <AddressForm history ={ history} ></AddressForm>
              </React.Fragment>
        </Paper>
      </main>
    </React.Fragment>
  );
}
Anticoagulant answered 8/6, 2021 at 7:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.