0

I'm learning React Router (protected routes, to be precise) and in React Router documentation there is a function which I almost understand but there is one line of code which I can't see how it works. Maybe someone can shortly describe what that line does. Below is a function from https://reactrouter.com/web/example/auth-workflow

function LoginPage() {
  let history = useHistory();
  let location = useLocation();

  let { from } = location.state || { from: { pathname: "/" } };
  let login = () => {
    fakeAuth.authenticate(() => {
        history.replace(from);
    });
  }; 

What does this line do?

let { from } = location.state || { from: { pathname: "/" } };

I understand that we are creating an object but what does || do? Is it connecting two objects into one? I don't get it.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Jules
  • 85
  • 1
  • 12
  • 1
    This is nothing to do with protected routes, React Router or even React. It's destructuring, with a default value provided to destructure out of in the case that `location.state` is null or undefined. See https://stackoverflow.com/q/2802055/3001761 for the right-hand side, https://stackoverflow.com/q/26999820/3001761 for the left-hand side. – jonrsharpe Jul 06 '20 at 16:31

1 Answers1

2

|| is the logical OR operator

let { from } = location.state || { from: { pathname: "/" } };

This is saying, assign location.state.from to the variable from if location.state is not null or undefined, else assign { pathname: "/" }

ludwiguer
  • 2,177
  • 2
  • 15
  • 21