/
login.js
50 lines (44 loc) · 1.31 KB
/
login.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
import axios from 'axios';
import actionTypes from '../actionTypes';
import setAuthorizationToken from '../../utils/setAuthorizationToken';
import { authLoading } from './signup';
import API from '../api';
import notify from '../notify';
/**
* @param {Object} user - user data
* @returns {Object} - Object containing action type and user
*/
export const loginUser = user => ({
type: actionTypes.LOGIN,
user,
});
/**
* @param {Boolean} status - status
* @returns {Object} - Object containing action type and login status
*/
export const setLoginStatus = status => ({
type: actionTypes.SET_LOGIN_STATUS,
isLoggedIn: status,
});
/**
* @param {object} data - user data
* @returns {any} - dispatches login user action
*/
export const login = data => (dispatch) => {
dispatch(authLoading(true));
return axios.post(`${API}/users/signin`, data)
.then((response) => {
const token = response.data.token;
localStorage.setItem('token', token);
setAuthorizationToken(token);
dispatch(loginUser(response.data));
dispatch(setLoginStatus(true));
dispatch(authLoading(false));
notify.success(response.data.message);
return response.data;
})
.catch((error) => {
notify.error(error.response.data.message);
return dispatch(authLoading(false));
});
};