Home > Back-end >  Property 'x' does not exist on type 'unknown'
Property 'x' does not exist on type 'unknown'

Time:03-08

I'm not quite getting this. I scoured through stackoverflow and github, and one of the solutions I tried was to add a generic but I'm getting this error Expected 0 type arguments, but got 1. under useLocation<LocationState> Here is my code below. The problem I'm having is setting types to {searchvalue} but its an unknown type. Any help would be greatly appreciated.

import React from "react";
import { useLocation } from "react-router-dom";

interface SearchResultsProps {}

interface LocationState {
    serachValue: string
}

export const SearchResults: React.FC<SearchResultsProps> = ({}) => {

    const location = useLocation<LocationState>();

     const {searchValue} = location.state
    

  return <div>Results Page</div>;

CodePudding user response:

Here's a link to the documentation for the useLocation hook from react-router-dom: https://reactrouter.com/docs/en/v6/api#uselocation

It defines the function signature as:

declare function useLocation(): Location;

interface Location extends Path {
  state: unknown;
  key: Key;
}

You can see that location.state is of type unknown, so if you have pushed data into the history state, and want to access it in a type-safe way, you can assert the type of data that you have pushed into the state like this:

const location = useLocation();
const {serachValue} = location.state as LocationState;

Here's a complete example:

TS Playground

import {default as React, type ReactElement} from 'react';
import {useLocation} from 'react-router-dom';

type EmptyObject = Record<never, never>;
type LocationState = { serachValue: string; };

function SearchResults (props: EmptyObject): ReactElement {
  const location = useLocation();
  const {serachValue} = location.state as LocationState;
//       ^^^^^^^^^^^
// is now type 'string'
  return (<div>Results Page</div>);
}

CodePudding user response:

useLocation isn't generically typed.

export function useLocation(): Location {
  invariant(
    useInRouterContext(),
    // TODO: This error is probably because they somehow have 2 versions of the
    // router loaded. We can help them understand how to avoid that.
    `useLocation() may be used only in the context of a <Router> component.`
  );

  return React.useContext(LocationContext).location;
}

Remove the <LocationState> and type the return value.

Example:

const { state }: { state: LocationState } = useLocation();
  • Related