Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useLocation doesn't recognize state

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>
);

I also tried to manage that as props, however there's another error that show it as if location wasn't recognized:

Here is the information of the second option about where I'm using Route and props to pass the information

function App() {
  return (
    <div className="App">
      <Navbar bg="dark"  variant="dark">
        <Navbar.Brand href="#home">
          Micrin
        </Navbar.Brand>
    </Navbar>
    <Router>
        <Switch>
          <Route path='/login' component={InicioSesion} />
          <Route path='/register' component={Registro} />
          <Route path='/recover' component={RecuperarCuenta}/>
          <Route path='/init/home' exact component={Logged} />
          <Route path='/init/stock' exact component={Logged}  />
          <Route path='/init/menu' exact component={Logged} />
          <Route path='/init/sales' exact component={Logged} />
          <Route path='/init/market' exact component={Logged} />
          <Route path='/' component={MainPage} />
        </Switch>
    </Router>
    </div>
  );
}

And the component rendering with props I sent

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); // Shows error message 'Property location does not exist on type {children?: ReactNode}'
        console.log(token);
});

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

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

return(
    <div></div>
);

Thank you for your help

like image 632
Andrés F Ariza Calderón Avatar asked Oct 21 '25 08:10

Andrés F Ariza Calderón


1 Answers

The second error you are getting is a Typescript error. It occurs because Typescript is not aware of the interface of your props.

When you define your component, you tell Typescript it is a React Functional component by writing:

const Logged: React.FC<{}>

Logged is a variable of type React.FC. The React.FC is a generic type. It means it can take an argument. This argument is the type of props your component accepts.

Here, you are telling Typescript that your component accepts no props at all: React.FC<{}>. So Typescript expect Logged to be basic React functional component (so it accepts only, eventually some children).

This is why Typescript complains when you try to get location from the props: Typescript doesn't expect to have such a prop:

enter image description here

You need to tell Typescript that this component accepts a location prop. You can do it by creating an interface like this:

interface Props {
  // your props here
  location;
}

const Logged: React.FC<Props> = ({ location }) => {
  // your code
}

(note: I also used props destructuring because I think it makes the code cleaner, but feel free to use props directly into your component)

But here, I just told Typescript there is a location variable, but I didn't explicitly set its type.

In your case, it is a bit more tricky because React Router is injecting these props for you. So in this case you can extend your Props interface like this:

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

import { StaticContext } from 'react-router';
import { RouteComponentProps } from 'react-router-dom';

type LocationState = {
  value: string;
};

interface Props extends RouteComponentProps<{}, StaticContext, LocationState> {
  // Here you can define the other props of your component
  // if needed
}

const Logged: React.FC<Props> = ({ location }) => {
  const [open, setOpen] = useState(false);
  const [token, setToken] = useState('');

  useEffect(() => {
    setToken(location.state.value);
  });

  return <div>Hello</div>;
};

export default Logged;

And now, because Typescript is aware of the type of your props, your IDE can also auto-complete: enter image description here

and it knows value is a string: enter image description here

I suggest you to take a look at this SO question: React Typescript: add location state to react router component

and to some "intro to typescript + react" tutorials such as this one: https://alligator.io/react/typescript-with-react/

Because you will get a lot of errors like this and when you know how to read them, it is not super hard to solve.

I think your first error is also related to some missing types but I could not understand the exact problem and reason with what you shared here.

like image 94
Hugo Avatar answered Oct 22 '25 21:10

Hugo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!