-
Notifications
You must be signed in to change notification settings - Fork 707
/
user.js
62 lines (55 loc) · 1.2 KB
/
user.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
import axios from 'axios'
import history from '../history'
/**
* ACTION TYPES
*/
const GET_USER = 'GET_USER'
const REMOVE_USER = 'REMOVE_USER'
/**
* INITIAL STATE
*/
const defaultUser = {}
/**
* ACTION CREATORS
*/
const getUser = user => ({type: GET_USER, user})
const removeUser = () => ({type: REMOVE_USER})
/**
* THUNK CREATORS
*/
export const me = () =>
dispatch =>
axios.get('/auth/me')
.then(res =>
dispatch(getUser(res.data || defaultUser)))
.catch(err => console.log(err))
export const auth = (email, password, method) =>
dispatch =>
axios.post(`/auth/${method}`, { email, password })
.then(res => {
dispatch(getUser(res.data))
history.push('/home')
})
.catch(error =>
dispatch(getUser({error})))
export const logout = () =>
dispatch =>
axios.post('/auth/logout')
.then(_ => {
dispatch(removeUser())
history.push('/login')
})
.catch(err => console.log(err))
/**
* REDUCER
*/
export default function (state = defaultUser, action) {
switch (action.type) {
case GET_USER:
return action.user
case REMOVE_USER:
return defaultUser
default:
return state
}
}