File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change
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 ;
You can’t perform that action at this time.
0 commit comments