Created
July 13, 2018 06:46
-
-
Save m0veax/6cf170bf8e3bffa5e424d9724b909362 to your computer and use it in GitHub Desktop.
trying to encapsulate a rest api in a backend class in a react-redux-thunk environment
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
import axios from 'axios'; | |
export default class backend { | |
constructor(username, password) { | |
this.client = axios.create({ | |
auth: { | |
username, | |
password | |
} | |
}); | |
this.username = username; | |
this.password = password; | |
this.loggedIn = false; | |
} | |
isLoggedIn() { | |
this.client.get('http://api.tld/isLoggedIn?secret=schmuuuu') | |
.then( | |
result => { | |
if (result.status === 200) { | |
this.loggedIn = true; | |
dispatch({ | |
type: 'LOGIN_SUCCESS', | |
credentials: { | |
username: this.username, | |
password: this.password | |
} | |
}) | |
} else { | |
dispatch({type: 'LOGIN_ERROR'}) | |
} | |
} | |
) | |
} | |
} |
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
import backend from '../backend'; | |
export const LOGIN_START = 'LOGIN_START'; | |
export const LOGIN_ERROR = 'LOGIN_ERROR'; | |
export const LOGIN_SUCCESS = 'LOGIN_SUCCESS'; | |
export const CHANGE_USERNAME = 'CHANGE_USERNAME'; | |
export const CHANGE_PASSWORD = 'CHANGE_PASSWORD'; | |
const client = new backend() | |
export function doLogin(username, password) { | |
console.log('doLogin'); | |
return dispatch => backend.doLogin(); | |
} | |
export function changeUsername(username) { | |
return { | |
type: CHANGE_USERNAME, | |
username | |
} | |
} | |
export function changePassword(password) { | |
return { | |
type: CHANGE_PASSWORD, | |
password | |
} | |
} |
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
import { createStore, combineReducers, applyMiddleware } from 'redux'; | |
import thunk from 'redux-thunk'; | |
import { LOGIN_START, LOGIN_SUCCESS, LOGIN_ERROR, CHANGE_USERNAME, CHANGE_PASSWORD } from './actions/LoginActions'; | |
function LoginReducer(state = { | |
username: '', | |
password: '', | |
isLoggedIn: false, | |
loggingIn: false, | |
}, action) { | |
switch(action.type) { | |
case CHANGE_USERNAME: | |
return { | |
...state, | |
username: action.username | |
}; | |
case CHANGE_PASSWORD: | |
return { | |
...state, | |
password: action.password | |
}; | |
default: | |
return { ...state }; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment