Home > Software design >  useLocation Hook returns wrong path
useLocation Hook returns wrong path

Time:05-19

I built an Ionic-React App that can scan a QR-Code and connect to a Device based on that. I use the useLocation() and useHistory() Hooks to route through my App.

I pass some Data like that:

    const Home: React.FC = () => {

  let history = useHistory()

  const startScan = async () => {
//Some Barcode Logic
 history.replace("/gatherData", {scan: result.content})
    }};

and recieve it using:

const GatherData: React.FC = () => {

    let history = useHistory();
    let location = useLocation();

    useIonViewWillEnter(() => {
        console.log(location);
    });

I did this, as usual and it seemed to be working quite nicely. But now, somehow, the useLocation() Hook does not recognize the history changing anymore. Although I get routed to the next page, the useLocation() returns an old path:

{pathname: '/home', ... state: undefined, key: 'bdwus9'}

I did try to recode the thing but that didn't solve the issue. Also trying to catch bugs in the HomeFC and in the GatherDataFC didn't help. It would be great if anyone had a solution to the problem...

CodePudding user response:

Your useIonViewWillEnter currently gets an obsolete state because it's cached, just like many other hooks. To fix this, you need to explicitly tell it that its dependency location was changed.

useIonViewWillEnter(() => {
    console.log(location);
}, [location]/*depdendency array*/);
  • Related