useLocation doesn't recognize the keys I'm sending, React

Viewed 652

Recently, I started to use React router and I learned that I can send variables through different components so I can use them in different parts of my app. However, I tried to implement the code and there is an error that doesn't let me use the variable where I' storing this value. So please if you can help me with this doubt:

Here is where I'm getting the error:

return(
    <div>
        <ToastContainer draggable={false} transition={Zoom} autoClose={8000}/>
        <h1>Iniciar sesión</h1>
        <Container placeholder>
            <Segment>
            <Form id='login'>
                <Form.Field>
                    <label>Nombre local:</label>
                    <input placeholder='Ingresa tu local' name='nombre' onChange={actualizarUser} required value={userLogin.nombre}/>
                </Form.Field>
                <Form.Field>
                    <label>Contraseña:</label>
                    <input placeholder='Ingresa tu contraseña' type='password' name='password' onChange={actualizarUser} required value={userLogin.password}/>
                </Form.Field>

                <Link to={{ pathname:'/init/home', state:{ Authorization: token } }}> //Here is where I'm sending the value token, where I storage a key to login
                    <Button type='submit'>SubmitNuevo</Button>
                </Link>
                <Button type='submit' onClick={sendInfo}>Prueba</Button>
            </Form>
            </Segment>
        </Container>

        <Modal show={success} onHide={handleClose}>
            <Modal.Header closeButton>
            <Modal.Title>Registro exitoso</Modal.Title>
            </Modal.Header>
            <Modal.Body>
                Su local se ha creado exitosamente. Ahora puede iniciar sesión.
            </Modal.Body>
            <Modal.Footer>
                <Button variant="secondary" onClick={handleClose}>
                    Cerrar
                </Button>
            </Modal.Footer>
        </Modal>
    </div>
);

And the component where I'm using it:

const Logged: React.FC<{}> = () => {

const location = useLocation();
const [open, setOpen] = useState(false);  
const [token, setToken] = useState('');

useEffect(() => {
        console.log(location.state);
        setToken(location.state.Authorization); //Here is where I'm trying to capture the value I'm sending
        console.log(token);
}, [token]);

// The rest of the code is here

}

Basically is like useLocation is specting a unique value, instead I'm sending key and value... I guess. Can you please help me to understand and fix the error I'm getting?

Thank you.

Here you can see clearly the error I'm getting

enter image description here

1 Answers

Well, you send it as key Authorization, but try to access it via key infoToken, infoToken is undefined. When you send route state, it is an object literal.

{
  pathname:'/init/home',
  state:{ Authorization: token },
}

To access this you need to access it as you do any other object in javascript

props.location.state.Authorization

It appears to be correct in your shared code snippet, but incorrect int he screen capture.

EDIT

You need to place location.state in the dependency array to trigger effect for location.state. You will also want to use a guard clause on the state object so you don't have any "... access of ... undefined..." errors, i.e. page reloads or user navigates directly to '/init/home'.

useEffect(() => {
  console.log(location.state);
  location.state && setToken(location.state.Authorization);
}, [location.state]);

note: remove the console.log of token so the linter doesn't falsely flag it as a dependency (put it in its own effect).

const Logged = () => {
  const history = useHistory();
  const location = useLocation();
  const [token, setToken] = useState("");

  useEffect(() => {
    console.log(token);
  });

  useEffect(() => {
    console.log(location.state);
    location.state && setToken(location.state.Authorization);
  }, [location.state]);

  return (
    <div>
      Token: {token}
      <button type="button" onClick={history.goBack}>
        Back
      </button>
    </div>
  );
};

Edit sending route state, access location.state

Related