todo/frontend/src/reducers/login.js

104 lines
2.5 KiB
JavaScript

import axios from 'axios';
import { createAction, createAsyncAction } from './utils';
import { createReducer } from '@reduxjs/toolkit';
import { updateLocalStorage } from './localStorage';
const actions = {
update: 'UPDATE_LOGIN_DETAILS'
};
const updateLoginDetails = createAction(actions.update, (payload) => {
return payload;
});
export const login = createAsyncAction((dispatch, getState, config, email, password) => {
axios
.post(`${config.apiUrl}/user/login`, {
email: email,
password: password
})
.then(
(success) => {
console.error('success', success);
dispatch(
updateLoginDetails({
id: success.data['userid'],
token: success.data['session_token'],
error: false
})
);
dispatch(
updateLocalStorage('userDetails', {
id: success.data['userid'],
token: success.data['session_token']
})
);
window.location.pathname = '/';
},
(reject) => {
console.error(reject);
dispatch(
updateLoginDetails({
id: undefined,
token: undefined,
error: true
})
);
dispatch(
updateLocalStorage('userDetails', {
id: undefined,
token: undefined
})
);
}
);
});
export const forgotPassword = createAsyncAction((dispatch, getState, config, email) => {});
export const logout = createAsyncAction((dispatch, getState, config) => {
const details = getState().login;
axios
.post(`${config.apiUrl}/user/logout`, {
userid: details.id,
session_token: details.token
})
.then(
(success) => {
dispatch(
updateLoginDetails({
id: undefined,
token: undefined,
error: false
})
);
dispatch(
updateLocalStorage('userDetails', {
id: undefined,
token: undefined
})
);
window.location.pathname = '/login';
},
(reject) => {
console.warn(reject);
console.warn('could not log out.');
}
);
});
export default createReducer(
{
id: undefined,
token: undefined,
error: false
},
(builder) => {
builder.addCase(actions.update, (state, action) => {
console.error(state, action);
state = { ...state, ...action?.payload };
});
}
);