Skip to content

Commit d064af9

Browse files
Create redux asyncThunkExample.ts
1 parent b92d1cb commit d064af9

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
2+
3+
const getWeatherData = (): Promise<object | Error> => {
4+
const appid = "getyourappidatopenweathermap.org";
5+
// add your location
6+
const lat = 0.0;
7+
const lon = 0.0;
8+
9+
return fetch(
10+
`https://api.openweathermap.org/data/2.5/forecast?appid=${appid}&lat=${lat}&lon=${lon}&units=metric`
11+
)
12+
.then((res) => {
13+
if (!res.ok) {
14+
console.error(
15+
"There was an error fetching the data, status is: " + res.status
16+
);
17+
throw new Error();
18+
}
19+
return res.json();
20+
})
21+
.catch((e) => {
22+
throw Error(`There was an error: ${e}`);
23+
});
24+
};
25+
26+
export const fetchWeatherByLocation = createAsyncThunk(
27+
"weather/location",
28+
async (_, thunkAPI) => {
29+
const response = await getWeatherData();
30+
if (response instanceof Error) return thunkAPI.rejectWithValue("error");
31+
32+
return response;
33+
}
34+
);
35+
36+
const locationSlice = createSlice({
37+
name: "location",
38+
initialState: {
39+
value: {},
40+
status: "idle",
41+
},
42+
reducers: {},
43+
extraReducers: (builder) => {
44+
builder
45+
.addCase(fetchWeatherByLocation.pending, (state) => {
46+
state.status = "loading";
47+
})
48+
.addCase(fetchWeatherByLocation.fulfilled, (state, action) => {
49+
state.status = "succeeded";
50+
if (action.payload) {
51+
state.value = action.payload;
52+
}
53+
})
54+
.addCase(fetchWeatherByLocation.rejected, (state) => {
55+
state.status = "failed";
56+
});
57+
},
58+
});
59+
60+
export default locationSlice.reducer;

0 commit comments

Comments
 (0)