I fetch data from API by using react-redux Toolkit. Want to display default city weather datas when page render but it gives an error
TypeError: Cannot read properties of undefined (reading 'name')
Output - > Empty Array from index.js than API output from WeatherSlice.js
export const fetchDefault = createAsyncThunk('weather/getWeather', async (selectedCity) => {
const res = await axios(`http://api.weatherapi.com/v1/forecast.json?key=ebb6c0feefc646f6aa6124922211211&q=${selectedCity}&days=10&aqi=no&alerts=no
`)
return res.data
});
<Typography className="label" variant="h5" sx={{pb:5}} component="div">
{getCity.location.name} // GivesTypeError
</Typography>
Home component
const getCity = useSelector((state) => state.weather.item);
useEffect(() => {
dispatch(fetchDefault(selectedCity))
console.log()
}, [dispatch])
App.js
<Switch>
<Route path="/about" component={About} >
<About />
</Route>
<Route path="/" component={Home}>
<Home />
</Route>
</Switch>
Store.js
export const store = configureStore({
reducer: {
weather : weatherSlice.reducer,
},
})
WeatherSlice.js
export const weatherSlice = createSlice({
name: "weather",
initialState : {
item : [],
},
reducers:{},
extraReducers:{
[fetchDefault.fulfilled]: (state , action) => {
state.item = action.payload;
console.log(state.item)
},
[fetchDefault.pending]: (state , action) => {
console.log("sadsad")
}
}
I checked the api you used (https://api.weatherapi.com/v1/forecast.json?key=ebb6c0feefc646f6aa6124922211211&q=Istanbul&days=10&aqi=no&alerts=no) to see what it returns.
Response data is an object with fields: location, current and forecast.
So at first, I think the initial state for "item" should not be an empty array because api does not returns an array instead it should be undefined or empty object.
Then, the main reason that the TypeError exists is you can not retrieve data or can not fill the item in the state. You should check the data that returns from the api. Can you successfully retrieve the data and fill the state with it?
Reason of TypeError: If you have an empty array or empty object and try to access a field through this element (like item.location) it will not show an error, but if you try to access a field of a field (like item.location.name) the TypeError occurs.
Also checking the object before component will be safer. Like:
// can be undefined comparison or getCity.length > 0 etc
{getCity !== undefined && (
<Typography className="label" variant="h5" sx={{pb:5}} component="div">
{getCity.location.name} // GivesTypeError
</Typography>
)}