useLocation doesn't recognize the state I sent

Viewed 490

I started to use react-router and I find out that I can pass 'props' in Link component so some values can pass to another component. I'm sending a component called 'value' inside the button I'm using, however in the component that receive that parameter show an error message with the message 'Object is possibly null or undefined'.

Here is my code:

Where I'm sending the data:

<Container placeholder>
            <Segment>
            <Form>
                <Form.Field>
                    <label>Correo</label>
                    <input placeholder='Ingresa tu correo' name='nombre' onChange={actualizarUser}/>
                </Form.Field>
                <Form.Field>
                    <label>Contraseña</label>
                    <input placeholder='Ingresa tu contraseña' name='password' onChange={actualizarUser}/>
                </Form.Field>

                <Link to={{ pathname:'/init/home', state:{ value: token } }}> // Here I'm sending the props to the next component
                    <Button type='submit'>SubmitNuevo</Button>
                </Link>
                <Button type='submit' onClick={sendInfo}>Prueba</Button>
            </Form>
            </Segment>
        </Container>

And the component where I receive location.state

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

const [open, setOpen] = useState(false);  
const location = useLocation(); // Here I'm using useLocation to capture the props I sent
const [token, setToken] = useState('');

useEffect(() => {
        console.log(location.state);
        setToken(location.state.value); // Here is were I'm getting the error message
        console.log(token);
});

const handleOpen = () => {
    setOpen(true);
}

const handleClose = () => {
    setOpen(false);
}

return(<div>

    </div>
);

Thank you for your help

1 Answers

You need to use props.location instead of useLocation();. Can you try this.

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

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

useEffect(() => {
        console.log(props.location.state);
        setToken(props.location.state.value); // Here is were I'm getting the error message
        console.log(token);
});

const handleOpen = () => {
    setOpen(true);
}

const handleClose = () => {
    setOpen(false);
}

return(<div>

    </div>
);

Related