Verthon
Verthon

Reputation: 3247

React Router typescript Property 'redirectUrl' does not exist on type '{}'

I would like to send state via history.push a part of url related to pagination to the login page. But I don't know how to type it in Login, so the typescript will understand what exactly state contains.

The error that I'm receiving:

Property 'redirectUrl' does not exist on type '{}'
if (!isAuthorized) {
   history.push({ pathname: AppRoute.login, state: { redirectUrl: 'page=2' } });

  return;
}

Login page

const history = useHistory();
const redirectState = history?.location?.state;

if (isAuthorized) {
    history.push({ pathname: AppRoute.home, search: redirectState?.redirectUrl })

    return;
}

Upvotes: 0

Views: 268

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187214

You are getting that error because you aren't calling history.push() correctly. It accepts a path and a state, as two separate arguments:

history.push(AppRoute.login, { redirectUrl: 'page=2' });

And then on the other side, you would type your useLocation call by passing it the it the state type you expect.

function LoginPage() {
  const location = useLocation<{ redirectUrl: string }>()
  console.log(location.state.redirectUrl) // typed as: { redirectUrl: string }
}

Playground

Upvotes: 1

Related Questions