preactjs / preact-router

:earth_americas: URL router for Preact.
http://npm.im/preact-router
MIT License
1.02k stars 155 forks source link

How do you get the query parameters from the URL in Preact using TypeScript #408

Closed se22as closed 2 years ago

se22as commented 2 years ago

If my app is called with the url: http://host;port?a=1&b=2 how do I get the values from the URL for a and b when I am coding in TypeScript?

Debugging, I see that when the code comes into the component for my route, the "this.props" contains a "matches" value which contains the a=1 and b=2.

export class MyComp extends Component {
  constructor() {
    super();
    console.log("constructor | this.props = ");
    console.log(this.props);

    console.log("constructor | this.props.matches.code = ");

    const { matches} = this.props;  <!---- this does not work
    const { a, b } = matches;

    console.log("a= ", a);
  }
  ...
  }

The highlighted line doesn't compile as TypeScript says "Property 'matches' does not exist on type 'Readonly<Attributes & { children?: ComponentChildren; ref?: Ref; }>'.ts(2339)" I do not know how to type that variable.

Examples I have seen for the preact-router is all about "path parameters" on the URL (i..e http://host:/port/a/b) and not "query parameters".

orangecoloured commented 2 years ago

I have kind of the same observation. The typing of the onChange event seems to be either incomplete or the actual onChange event contains excess data.

rschristian commented 2 years ago

Component is a generic, you need to specify the type it takes.

type Props = {
    matches: {
        a: string;
        b: string;
    }
}

export class MyComp extends Component<Props> {
    constructor(props) {
        super(props);
        const { matches } = this.props;
        const { a, b } = matches;
    }
   ...
}