Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ReactJS trying to get params but I get property 'id' does not exist on type '{}'

Here are the routes. I am trying to get the param like /fetchdata/someid and I tried this.props.match.params.id this is where is says that:

property 'id' does not exist on type '{}'

import * as React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import { Layout } from './components/Layout';
import { Home } from './components/containers/Home';
import FetchData from './components/FetchData';
import { Counter } from './components/Counter';

export const routes =
    <Layout>  
        <Route exact path='/' component={Home} />
        <Route path='/counter' component={Counter} />
        <Route path='/fetchdata/:id/:param2?' component={FetchData} />    
    </Layout>;

FetchData Component It looks like that the param id is in the match but i cannot get it. :/ I think i miss passing {match}? But i not sure on how to do it :/. Can somebody help me out? I use react-router": "4.0.12".

import * as React from 'react';
import { RouteComponentProps, matchPath } from 'react-router';
import 'isomorphic-fetch';
//import FetchDataLoaded from './FetchDataLoaded';
import { withRouter } from 'react-router-dom';
import queryString from 'query-string';

interface FetchDataExampleState {
    forecasts: WeatherForecast[];
    loading: boolean;
    lazyloadedComponent;
    id;
}
//const queryString = require('query-string');

class FetchData extends React.Component<RouteComponentProps<{}>, FetchDataExampleState> {
    constructor(props) {
        super(props);

        this.state = { forecasts: [], loading: true, lazyloadedComponent: <div>Getting it</div>, id: "" };

        fetch('api/SampleData/WeatherForecasts')
            .then(response => response.json() as Promise<WeatherForecast[]>)
            .then(data => {
                this.setState({ forecasts: data, loading: false });
            });
    }

    async componentDidMount() {
        try {
            //let params = this.props.match.params
            //const idquery = queryString.parse(this.props.location .).id;
           //const idquery = queryString.parse(this.props.match.params).id;
            //const idquery = this.props.match.params.id;
            const idParam = this.props.match.params.id
            this.setState({
                id: idParam                
            })
            const lazyLoadedComponentModule = await import('./FetchDataLoaded');
            this.setState({ lazyloadedComponent: React.createElement(lazyLoadedComponentModule.default) })
        }
        catch (err) {
            this.setState({
                lazyloadedComponent: <div>${err}</div>
            })
        }    
    }    
    public render() {
        let contents = this.state.loading
            ? <p><em>Loading...</em></p>
            : FetchData.renderForecastsTable(this.state.forecasts);

        return <div>
            <div>Id: {this.state.id}</div>
            {this.state.lazyloadedComponent}
            <h1>Weather forecast</h1>
            <p>This component demonstrates fetching data from the server.</p>
            {contents}
        </div>;
    }

    private static renderForecastsTable(forecasts: WeatherForecast[]) {

        return <table className='table'>
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Temp. (C)</th>
                    <th>Temp. (F)</th>
                    <th>Summary</th>
                </tr>
            </thead>
            <tbody>
                {forecasts.map(forecast =>
                    <tr key={forecast.dateFormatted}>
                        <td>{forecast.dateFormatted}</td>
                        <td>{forecast.temperatureC}</td>
                        <td>{forecast.temperatureF}</td>
                        <td>{forecast.summary}</td>
                    </tr>
                )}
            </tbody>
        </table>;
    }
}
export default withRouter(FetchData)
interface WeatherForecast {
    dateFormatted: string;
    temperatureC: number;
    temperatureF: number;
    summary: string;
}
like image 389
vkampouris Avatar asked Apr 26 '18 16:04

vkampouris


3 Answers

You can specify the type of the matched route parameters in the type parameter of RouteComponentProps, so the error should disappear if you replace

class FetchData extends React.Component<RouteComponentProps<{}>, FetchDataExampleState> {

with

interface RouteParams {id: string, param2?: string}
class FetchData extends React.Component<RouteComponentProps<RouteParams>, FetchDataExampleState> {
like image 199
Oblosys Avatar answered Nov 12 '22 13:11

Oblosys


For hooks:

export interface IUserPublicProfileRouteParams {
    userId: string;
    userName: string;
}

const {userId, userName} = useParams<IUserPublicProfileRouteParams>();
like image 21
Stanislav Glushak Avatar answered Nov 12 '22 13:11

Stanislav Glushak


With a React Function Component this would work:

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

export interface AuditCompareRouteParams {
  fileType: string;
}

export const Compare = ({ match }: { match: match<AuditCompareRouteParams> }) => {
  console.log(match.params.fileType);
};
like image 4
Gus Avatar answered Nov 12 '22 12:11

Gus