I'm receiving this error in my terminal although my code and tests are running fine:
src/components/Weather.tsx:31
setWeather(response.data.result.weather);
^
TypeError: Cannot read properties of undefined (reading 'data')
at fetchWeatherData
I've looked for some answers online and it is quite broad most seem to be typos but I don't think that's the case here.
This is my component:
import axios from 'axios';
import { useEffect, useState } from 'react';
import { IWeather } from '../interfaces/IWeather';
import { MdWbSunny } from 'react-icons/md';
import { IoIosPartlySunny } from 'react-icons/io';
import { BsFillCloudSnowFill } from 'react-icons/bs';
import { Title, Text } from '@mantine/core';
const Weather = () => {
const [weather, setWeather] = useState<IWeather | null>();
const fetchWeatherData = async () => {
const response = await axios.get('http://mock-api-call/weather/get-weather');
setWeather(response.data.result.weather);
};
useEffect(() => {
fetchWeatherData();
}, []);
return (
<div className="container">
<>
<Title order={2}>
{weather?.forcast === 'Sunny' ? (
<MdWbSunny />
) : weather?.forcast === 'Snowing' ? (
<BsFillCloudSnowFill />
) : (
<IoIosPartlySunny />
)}
</Title>
</>
<Text size="xl">{weather?.forcast}</Text>
<Text size="lg">Temp: {`${weather?.min} to ${weather?.max}`}</Text>
<Text size="md">{weather?.description}</Text>
</div>
);
};
export default Weather;
the error is mentioning line 31. Which is this block in the Weather component:
<Title order={2}>
{weather?.forcast === 'Sunny' ? (
<MdWbSunny />
) : weather?.forcast === 'Snowing' ? (
<BsFillCloudSnowFill />
) : (
<IoIosPartlySunny />
)}
</Title>
CodePudding user response:
Try to debug like so :
const fetchWeatherData = async () => {
const response = await axios.get('http://mock-api-call/weather/get-weather', (request, response) => {
console.log('request', request);
console.log('response', response);
setWeather(response.data.result.weather);
});
};
Cheers
CodePudding user response:
It seems like it's not a valid api url, in order to detect what the issue is , i would like to add try/catch block to the fetch function :
const fetchWeatherData = async () => {
try {
const response = await axios.get('http://mock-api-call/weather/get-weather');
// Just put some log to ensure you have the response.
const {data} = response;
if (data?.result?.weather) {
setWeather(data?.result?.weather);
}
} catch(error) {
console.log("An Error is occured : ", error);
}
};