Last active
July 11, 2018 18:13
-
-
Save raikusy/25bf72f7528ca6f226a578b0236c8ba8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
** These are two actions for user login & logout. | |
** login action makes a api POST request with email & password in body. | |
** The reponse contains user id, token & a unique socket channel for current user. | |
** example => response: { data: { channelName: 'uniqueChannel', id: 1, token: 'JWT-TOKEN' } } | |
** logout action makes a api GET request with | |
** user id & token in header. | |
*/ | |
// See the socket middleware - https://gist.github.com/r4iku/bbe4c036afdffdc1ed73b3cedb8b4d3b | |
export function doLogin(values) { | |
return dispatch => { | |
const url = 'http://localhost/api/v1/login'; | |
fetch(url, { | |
method: 'POST', | |
body: JSON.stringify(values), // values: {email: 'user@email.com', password: 'pass123'} | |
headers: new Headers({ | |
'Content-Type': 'application/json', | |
}), | |
}) | |
.then(res => res.json()) | |
.catch(error => console.log(error)) | |
.then(response => { | |
if (response.error) { | |
dispatch(loginFailure(response.error)); | |
} else { | |
// If login success, dispatch the socket action with response.data as payload. | |
dispatch({type: 'SOCKET_CONNECT', payload: response.data,}); | |
dispatch(loginSuccess(response)); | |
} | |
}); | |
}; | |
} | |
export function doLogout(loginData) { | |
return dispatch => { | |
const url = 'http://localhost/api/v1/logout'; | |
fetch(url, { | |
method: 'GET', | |
headers: new Headers({ | |
Authorization: loginData.token, | |
id: loginData.id, | |
}), | |
}) | |
.then(res => res.json()) | |
.catch(error => console.log(error)) | |
.then(response => { | |
// If logout success, dispatch the socket action with channelName as payload. | |
// Passing loginData as payload because it contains the channelName | |
dispatch({ type: 'SOCKET_CLOSE', payload: loginData }); | |
dispatch(logoutSuccess()); | |
}); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment