Skip to content

Instantly share code, notes, and snippets.

@heytulsiprasad
Last active July 12, 2020 21:06
Show Gist options
  • Select an option

  • Save heytulsiprasad/cca889f714c3bcdb5137039c51642203 to your computer and use it in GitHub Desktop.

Select an option

Save heytulsiprasad/cca889f714c3bcdb5137039c51642203 to your computer and use it in GitHub Desktop.
Actions that we need to perform for basic React auth. (We use Redux)
// get user when needed by this
export const getUser = () => (dispatch, getState) => {
// User loading
dispatch({ type: "USER_LOADING"})
axios
.get('/api/auth/user', tokenConfig(getState))
.then(res => {
dispatch({
type: "USER_LOADED",
payload: res.data
})
})
.catch(err => {
dispatch({
type: "AUTH_ERROR",
payload: { ...err } // message, status, id
})
})
}
// Register user for the first time
export const register = () => dispatch => {
// 1. Set Headers
const config = {
headers: {
'Content-Type': 'application/json',
},
};
// 2. Send data inside body (after converting to JSON)
const body = JSON.stringify({ name, email, password });
axios
.post('/api/users', body, config)
.then((res) =>
dispatch({
// 3. Handle registeration status before and after post request
type: 'REGISTER_SUCCESS',
payload: res.data,
})
)
// 4. Handle promise errors with catch and set error msg to state
.catch((err) => {
dispatch({
type: "AUTH_ERROR",
payload: { ...err } // message, status, id
})
dispatch({
type: 'REGISTER_FAIL',
});
});
}
// LOGIN Route
// The difference b/w login and register is the data that's passed in body
// In login we don't pass the name of user
// Also, the route to which we're making the post request
export const login = () => dispatch => {
// 1. Set Headers
const config = {
headers: {
'Content-Type': 'application/json',
},
};
// 2. Send data inside body (after converting to JSON)
const body = JSON.stringify({ email, password });
axios
.post('/api/users', body, config)
.then((res) =>
dispatch({
// 3. Handle registeration status before and after post request
type: 'LOGIN_SUCCESS',
payload: res.data,
})
)
// 4. Handle promise errors with catch and set error msg to state
.catch((err) => {
dispatch({
type: "AUTH_ERROR",
payload: { ...err } // message, status, id
})
dispatch({
type: 'LOGIN_FAIL',
});
});
}
// LOGOUT
// This just sets everything in state to null or default values (of unauthorized user)
export const login = () => ({ type: 'LOGOUT_USER' })
// we use this to get token and pass it with header on our requests
// added this locally
export const tokenConfig = (getState) => {
// Getting our token from state (redux store, here)
const token = getState().auth.token;
// Pass default headers
const config = {
headers: {
"Content-Type": "application/json"
}
}
// If we have our token, then let's pass it with header
if (token) config.headers["x-auth-token"] = token
return config;
}
// we use it authActions.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment