Home > other >  In React, replacing URL with an identical value causes infinite loop
In React, replacing URL with an identical value causes infinite loop

Time:02-23

      if (new_path !== window.location.pathname   window.location.search) {
        history.replace({
          pathname: new_path,
          search: "",
        });
      }

EDITED:

new_path is just a string. Without the if statement, the above code will cause infinite loop.

Is that expected behavior?

CodePudding user response:

It will only cause an infinite loop if

new_path is different than window.location.pathname window.location.search.

If you want to check its values, try to preserve logs on chrome developer tools and then start your app. That way you can see why it is generating an infinite loop.

CodePudding user response:

If new_path is a state in your app it should be in {}

pathname: {new_path}

CodePudding user response:

The "if" condition is the wrong one.

if (new_path !== window.location.pathname   window.location.search) {}

This will be true always and history.replace will run again.

so the solution is

if (new_path[<your key>] !== window.location[<your key>]) {}

If you meant to be the new_path is a string, you need to check what is the new_path value

  • Related