0

Why is below code not working? It returns false even when I set inverted to true; it also logs hit so it does reach.

import React, { useEffect, useState } from 'react';
import { ComponentProps } from 'react';

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

type Props = {
} & ComponentProps<'div'>;

export function HeaderMaster({
  ...props
}: Props) {
  const [inverted, setInverted] = useState(false);
  const history = useHistory() 

   useEffect(() => {
    setInverted(true); // this does work
      history.listen((location) => { 
        console.log(location.pathname);
         if (location.pathname === '/bestellen') {
           setInverted(true); // this does not
           console.log('hit');
         }
         else {
          setInverted(false);
         }
      }) 

   },[history]);

   useEffect(() => {
    console.log(inverted);
  },[inverted]) 

  return (
    <>
    </>
  );
}
Raymond the Developer
  • 1,576
  • 5
  • 26
  • 57
  • 1
    the component may get unmounted once the location changes? – tanmay Oct 31 '20 at 06:37
  • Not sure what you mean by that can you explain more – Raymond the Developer Oct 31 '20 at 06:40
  • Do you have any debugging details? Can you provide a more complete component example? Could you try reproducing this into a *running* codesandbox? – Drew Reese Oct 31 '20 at 06:40
  • There is not much to add. I also testen setInverted outside of the listener and that does work – Raymond the Developer Oct 31 '20 at 06:43
  • 1
    @RaymondtheDeveloper so you have this listener on history inside a component.. which will stay mounted as long as you are on the current location.. you change the location, which may lead to current component getting unmounted.. hence the useEffect on inverted doesn't trigger.. that's my best guess with given code – tanmay Oct 31 '20 at 06:44
  • 1
    @tanmay you are correct I removed the whole listener and put the if else outside. That does work. I got that code from a tutorial not sure why he did it like this. Thanks! – Raymond the Developer Oct 31 '20 at 06:51
  • Do you have an example how this component is used? What is rendering it? – Drew Reese Oct 31 '20 at 06:53
  • I got it from this tutorial: https://help.mouseflow.com/en/articles/4310818-tracking-url-changes-with-react But it's solved already thanks – Raymond the Developer Oct 31 '20 at 17:19

0 Answers0