zdd
zdd

Reputation: 8727

React useHistory, Object is of type 'unknown'

I got error Object is of type 'unknown' when using react hook useHisotry, here is the details, thanks in advance for your help!

Node version: v12.14.1

React version: 17.0.1

react-router-dom version: 16.9.8

@types of react-router-dome version: ^5.1.6

import { useHistory } from "react-router-dom";
const history = useHistory();

useEffect(() => {
    if (history.location.state) {
      const taskId: any = history.location.state.taskId
      getItemList(taskId)
    }
  }, [])

// Error message

  Object is of type 'unknown'.  TS2571

    252 |   useEffect(() => {
    253 |     if (history.location.state) {
  > 254 |       const taskId: any = history.location.state.taskId
        |                           ^
    257 |     }

Upvotes: 1

Views: 3527

Answers (3)

Giovanni Benussi
Giovanni Benussi

Reputation: 3500

You need to define the type of the state object like this:

const history = useHistory<{ taskId: string }>();
const taskId = history.location.state.taskId

Upvotes: 1

ShwetaJ
ShwetaJ

Reputation: 519

I was trying to do something similar to get the previous URL from which the current component has been navigated to.

Here is what I did:

In the component where you push the url in the history object:

 history.push(`/overview`, {
      from: '/map',
    } as { from: string });

Now, in the component where you want to use the history object:

const history = useHistory();
const state = history.location.state as { from: string }

console.log(state.from); // this will give you the value from the state

In your case, replace "from" with "taskId".

I hope that helps. Since you define what properties to include in the location state, it is safe to define a type for it.

Upvotes: 4

Peter Mugendi
Peter Mugendi

Reputation: 945

You should consider get history from props instead. https://reactrouter.com/web/api/history/history-is-mutable See the example below.

export default function ExampleComponent(props: any) {

const { taskId } = props.history.location.state;

 console.log(taskId);

}

if you don't want to use props consider using useLocation hook . The useLocation hook returns the location object that represents the current URL. You can think about it like a useState that returns a new location whenever the URL changes. https://reactrouter.com/web/api/Hooks/uselocation


import {useLocation} from "react-router-dom";
export default function ExampleComponent(props: any) {
 let location = useLocation();
const { taskId } = location.state;

  console.log(taskId);

}

Upvotes: -1

Related Questions