-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathasyncthunk.js
More file actions
75 lines (62 loc) · 1.61 KB
/
asyncthunk.js
File metadata and controls
75 lines (62 loc) · 1.61 KB
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
const redux= require('redux');
const createStore= redux.createStore;
const applyMiddleware =redux.applyMiddleware;
const thunkMiddleware=require('redux-thunk').default;
const axios = require('axios');
const initialState={
loading:false,
users:[],
error:''
}
const USER_REQUEST='USER_REQUEST';
const USER_SUCCESS='USER_SUCCESS';
const USER_ERROR='USER_ERROR';
const userRequest=()=>{
return{
type:USER_REQUEST
}
}
const userSuccess=(users)=>{
return{
type:USER_SUCCESS,
payload:users
}
}
const userError=(error)=>{
return{
type:USER_ERROR,
payload:error
}
}
const reducer=(state=initialState,action)=>{
switch(action.type){
case "USER_REQUEST": return{
...state, loading:true
}
case "USER_SUCCESS": return{
loading:false, users:action.payload,error:''
}
case "USER_ERROR": return{
loading:false, users:[],error:action.payload
}
}
}
const fetchUser=()=>{
return function(dispatch){
dispatch(userRequest())
axios.get('https://jsonplaceholder.typicode.com/users')
.then(response=>{
// response.data
const users =response.data.map(user=>user.name)
dispatch(userSuccess(users))
})
.catch(error=>{
// error.message
dispatch(userError(error.message))
})
}
}
const store =createStore(reducer,applyMiddleware(thunkMiddleware));
const unsubscribe=store.subscribe(()=>{console.log(store.getState())});
store.dispatch(fetchUser());
//unsubscribe();