-
Notifications
You must be signed in to change notification settings - Fork 0
/
IndexThunk.js
85 lines (72 loc) · 2.11 KB
/
IndexThunk.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const redux = require('redux')
const ReduxThunk = require('redux-thunk').default
const axios = require('axios')
const createStore = redux.createStore
const applyMiddleware = redux.applyMiddleware
const fetch_user_request = "fetch_user_request"
const fetch_user_success = 'fetch_user_success'
const fetch_error = 'fetch_error'
// actions
const fetchUserReq = () =>{
return {
type : fetch_user_request // types are required to identify the switch statement when it is dispatch(action creator)
}
}
const fetchUserSucc = (users) =>{
return {
type : fetch_user_success ,
payload : users
}
}
const fetchError = (error) =>{
return {
type : fetch_error,
payload : error
}
}
const initialState = {
loading : true,
users : [],
error : ''
}
// reducer
const reducer = (state = initialState , action) => {
switch(action.type){
case fetch_user_request : return {
...state ,
loading : true
}
case fetch_user_success : return{
...state ,
loading : false ,
users : action.payload,
error : ''
}
case fetch_error : return {
...state ,
loading : false ,
users : [] ,
error : action.payload
}
}
}
// action creator
const FetchUsers = () =>{
return function(dispatch){
// get users from API
dispatch(fetchUserReq())
axios.get('https://jsonplaceholder.typicode.com/users')
.then(Response => {
// if response is came then assign the users from api to users array
const users = Response.data.map(user => user.id)
dispatch(fetchUserSucc(users))
})
.catch(error => {
// If error occured
dispatch(fetchError(error.message))
})
}
}
const store = createStore(reducer , applyMiddleware(ReduxThunk))
store.subscribe(()=>{console.log("Current State : ",store.getState())})
store.dispatch(FetchUsers())