Skip to content

Instantly share code, notes, and snippets.

@Acetyld
Created February 19, 2020 22:31
Show Gist options
  • Save Acetyld/cc914fbbafe17c7f7266c4158d559c19 to your computer and use it in GitHub Desktop.
Save Acetyld/cc914fbbafe17c7f7266c4158d559c19 to your computer and use it in GitHub Desktop.
import { createSlice } from '@reduxjs/toolkit';
import api from "../../../components/api";
import {Platform} from "react-native";
import {errorHandler} from "../../services/ErrorHandler";
export const slice = createSlice({
name: 'authenticate',
initialState: {
token: null,
},
reducers: {
api_login: (state,action) => {
// Redux Toolkit allows us to 'mutate' the state. It doesn't actually
// mutate the state because it uses the immer library, which detects
// changes to a "draft state" and produces a brand new immutable state
// based off those changes
state.token = action.payload;
},
},
});
export const authenticate = deviceId => async (dispatch, getState) => {
/*Trying to login attempt one*/
let loginResult;
try {
loginResult = await apiLogin(deviceId);
dispatch(slice.actions.api_login(loginResult.data.token));
return;
} catch (e) {
let error = errorHandler(e, 'Login attempt one');
if (error.status !== 401) {
return Promise.reject(error);
}
}
/*Trying to register attempt one*/
try {
await apiRegister(deviceId);
} catch (e) {
let error = errorHandler(e, 'Register attempt one');
if (error.status !== 401) {
return Promise.reject(error);
}
}
/*Trying to login attempt two*/
let loginResultTwo;
try {
loginResultTwo = await apiLogin(deviceId);
dispatch(slice.actions.api_login(loginResultTwo.data.token));
return;
} catch (e) {
let error = errorHandler(e, 'Login attempt two');
if (error.status !== 401) {
return Promise.reject(error);
}
}
};
const apiLogin = deviceId => {
return api.post('/login_check', {
username: deviceId,
password: deviceId,
});
};
const apiRegister = deviceId => {
return api.post('/register', {
username: deviceId,
password: deviceId,
os: Platform.OS,
});
};
export const token = state => state.authenticate.token;
export default slice.reducer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment