J'ai deux erreurs uniquement lorsque l'application est déployée, pas en mode dev ni en build local, ce qui est un tout autre problème.
1ère erreur : Le contenu du texte ne correspond pas au HTML rendu par le serveur.
2ème erreur : Il y a eu une erreur pendant l'hydratation. Comme l'erreur s'est produite à l'extérieur d'une zone de suspense, la racine entière va passer au rendu client.
J'ai découvert que les erreurs sont causées par le formatage de l'heure que je reçois d'une API au format timestamp Unix (current.dt), mais je ne sais pas comment gérer cela autrement. Devrais-je formater la date sur le serveur, c'est-à-dire dans getServerSideProps ? Ou ces erreurs sont-elles dues à autre chose ?
Editar : Application en direct avec des erreurs : https://weather-test-mu.vercel.app/
Affichage du temps :
import type { Current, Location } from '../../types/typeWeatherApi';
const WeatherDisplay = ({
location,
current,
}: {
location: Location;
current: Current;
}) => {
// This causes the errors:
const hour = ('0' + new Date(current.dt * 1000).getHours()).slice(-2);
const minutes = ('0' + new Date(current.dt * 1000).getMinutes()).slice(-2);
const currentTime = `${hour}:${minutes}`;
return (
<article>
<h1>{location.name}</h1>
<p>{location.country}</p>
<p>{current.feels_like}</p>
{/* This causes the error: */}
<p>{currentTime}</p>
</article>
);
};
export default WeatherDisplay;
Page d'index avec getServerSideProps :
import axios from 'axios';
import { useState } from 'react';
import type { NextPage, GetServerSideProps } from 'next';
import type { Data, Location } from '../types/typeWeatherApi';
import { getCurrentWeather } from './api/currentWeather';
import { getCurrentLocation } from './api/currentLocation';
import WeatherDisplay from '../components/weather-display/weather-display';
const Home: NextPage = ({ initialWeather, initialLocation }: any) => {
const [location, setLocation] = useState<Location>(initialLocation);
const [weatherData, setWeatherData] = useState<Data>(initialWeather);
const [units, setUnits] = useState('metric');
const [lang, setLang] = useState('en');
const getGeolocationData = () => {
navigator.geolocation.getCurrentPosition(
(position) => {
axios
.get(
`/api/currentLocation?lon=${position.coords.longitude}&lat=${position.coords.latitude}`
)
.then((response) => setLocation(response.data[0]));
},
(error) => {
console.warn(`ERROR(${error.code}): ${error.message}`);
},
{
timeout: 10000,
maximumAge: 0,
}
);
};
const getCurrentWeather = async () => {
await axios
.get(
`/api/currentWeather?lon=${location.lon}&lat=${location.lat}&units=${units}&lang=${lang}`
)
.then((response) => setWeatherData(response.data))
.catch((error) => console.error(error));
};
return (
<>
<section>
<div>
<p>Latitude: {location.lat}</p>
<p>Longitude: {location.lon}</p>
</div>
<button onClick={getGeolocationData}>Get Current Location</button>
<button onClick={getCurrentWeather}>Get Current Weather</button>
</section>
<section className="current-weather">
<WeatherDisplay location={location} current={weatherData.current} />
</section>
</>
);
};
export const getServerSideProps: GetServerSideProps = async () => {
const defaultWeatherQuery = {
lat: '51.5072',
lon: '0.1276',
exclude: '',
units: 'metric',
lang: 'en',
};
const defaultLocationQuery = {
lat: defaultWeatherQuery.lat,
lon: defaultWeatherQuery.lon,
};
const defaultWeather = await getCurrentWeather(defaultWeatherQuery);
const defaultLocation = await getCurrentLocation(defaultLocationQuery);
return {
props: {
initialWeather: defaultWeather,
initialLocation: defaultLocation[0],
},
};
};
export default Home;