I am new to typescript, I am making a weather app using open weather API, I am giving a call to API and setting the state of API response (weatherData
here), but the typescript is not allowing me to pass the state as props to other component and gives error Property 'name' does not exist on type 'Object'
. I previously made weather app using react js and didn't face any problem but this react typescript really sucks, very difficult to deal with types, please help me.
Am I not using best practices of typescript? please suggest any resources.
import React, { Component, Fragment } from "react";
import { Search } from './Search';
import { CityAndDate } from "./CityAndDate";
import { Status } from "./Status";
import { TemperatureMsg } from "./TemperatureMsg";
import { SunriseAndSunset } from "./SunriseAndSunset";
import { Details } from "./Details";
import axios from "axios";
import './app.scss';
interface AppProps {};
interface ApiResponse {
response: object;
data: object;
};
interface AppState {
weatherData: Object;
};
class App extends Component<AppProps, AppState> {
constructor(props: AppProps) {
super(props);
this.state = {
weatherData: {}
}
}
enterKeyPress = (searchValue: string): void => {
console.log(searchValue, 'searchValue');
const getWeatherDataByCity = async (city: string) => {
const response: ApiResponse = await axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=#######&units=metric`);
this.setState({ weatherData: response.data });
}
getWeatherDataByCity(searchValue);
}
render() {
console.log(this.state, 'state')
const { weatherData } = this.state;
return(
<Fragment>
<div className="row justify-content-lg-end justify-content-md-end justify-content-sm-center">
<div className="col-lg-2 col-md-4 col-sm-4"><Search enterKeyPress={this.enterKeyPress} /></div>
</div>
<div className="container">
<div className="row justify-content-center m-3">
<div className="col-lg-3 col-md-4 col-sm-4">
<CityAndDate city={weatherData.name} /> // Getting error here
</div>
</div>
<div className="row justify-content-lg-start justify-content-md-start justify-content-sm-center small-screen-container mt-5">
<div className="col-lg-3 col-md-4 col-sm-4"><Status /></div>
</div>
<div className="row justify-content-lg-between justify-content-md-between justify-content-sm-center mt-2">
<div className="col-lg-3 col-md-4 col-sm-8"><TemperatureMsg /></div>
<div className="col-lg-3 col-md-4 col-sm-8 sm-mt-10"><SunriseAndSunset /></div>
</div>
<div className="row mt-5">
<div className=""><Details /></div>
</div>
</div>
</Fragment>
);
}
}
export default App;
CodePudding user response:
You should create a type of WeatherObject
with the properties defined and assign this type (instead of an ambigous Object
) to your weatherObject
.