mirror of
https://github.com/aspnet/JavaScriptServices.git
synced 2025-12-23 01:58:29 +00:00
Add data-loading example to ReactSpa template, and remove server-side rendering (because you really need Redux/Flux or similar for that to make sense)
This commit is contained in:
62
templates/ReactSpa/ClientApp/components/FetchData.tsx
Normal file
62
templates/ReactSpa/ClientApp/components/FetchData.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
import * as React from 'react';
|
||||
|
||||
interface FetchDataExampleState {
|
||||
forecasts: WeatherForecast[];
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
export class FetchData extends React.Component<void, FetchDataExampleState> {
|
||||
constructor() {
|
||||
super();
|
||||
this.state = { forecasts: [], loading: true };
|
||||
|
||||
fetch('/api/SampleData/WeatherForecasts')
|
||||
.then(response => response.json())
|
||||
.then((data: WeatherForecast[]) => {
|
||||
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 }
|
||||
<p>For more sophisticated applications, consider an architecture such as Redux or Flux for managing state. You can generate an ASP.NET Core application with React and Redux using <code>dotnet new aspnet/spa/reactredux</code> instead of using this template.</p>
|
||||
</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;
|
||||
}
|
||||
Reference in New Issue
Block a user