Created
February 28, 2018 21:28
-
-
Save nathandaly/6dc0bced2f9482aa41444b55f9703f17 to your computer and use it in GitHub Desktop.
.NET Core React fetching data example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
import { RouteComponentProps } from 'react-router'; | |
import 'isomorphic-fetch'; | |
interface FetchDataExampleState { | |
forecasts: WeatherForecast[]; | |
loading: boolean; | |
} | |
export class FetchData extends React.Component<RouteComponentProps<{}>, FetchDataExampleState> { | |
constructor() { | |
super(); | |
this.state = { forecasts: [], loading: true }; | |
fetch('api/SampleData/WeatherForecasts') | |
.then(response => response.json() as Promise<WeatherForecast[]>) | |
.then(data => { | |
this.setState({ forecasts: data, loading: false }); | |
}); | |
} | |
public render() { | |
let contents = this.state.loading | |
? <p><em>Loading...</em></p> | |
: FetchData.renderForecastsTable(this.state.forecasts); | |
return <div> | |
<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>; | |
} | |
} | |
interface WeatherForecast { | |
dateFormatted: string; | |
temperatureC: number; | |
temperatureF: number; | |
summary: string; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment