Как отловить ошибку в action redux
У меня есть такой код запрос к сервису openweathermap.org
export const getWeather = (city) => async (dispatch) => {
const res = await weather.getWeather(city)
if(res.ok) {
dispatch(setWeather(res.data)) // res data is undefined. WHY?
} else {
dispatch(setError(res))
}
}
const setError = (error) => ({
type: "SET_ERROR",
payload: error
})
export const setWeather = (weather) => ({
type: "SET_WEATHER",
payload: weather
})
Даже если я каким то образом не могу получить res.data, то как мне обработать ошибку через promise и then?
Так же у меня есть service который делает fetch запрос
const weather = {
getWeather: async (city: string) => {
const res = await fetch(api + `?=${city}` + `&appid=${apiKey}`);
return res;
}
}
Как мне обработать ошибку в action getWeather чтобы эту ошибку положить в состояние redux?
const initialValue = {
weather: {},
isLoaded: false,
errors: {}
}
const weather = (state = initialValue, action) => {
switch (action.type) {
case "SET_WEATHER":
return {
...initialValue,
weather: action.payload
}
case "SET_ERROR":
return {
...initialValue,
errors: action.payload
}
default: return state;
}
}