Skip to content

Instantly share code, notes, and snippets.

@khanof89
Created May 16, 2020 16:13
Show Gist options
  • Save khanof89/0348e9ea4bd430101ccdb96fae5306ee to your computer and use it in GitHub Desktop.
Save khanof89/0348e9ea4bd430101ccdb96fae5306ee to your computer and use it in GitHub Desktop.
========= store =========
import {applyMiddleware, compose, createStore} from 'redux';
import {createLogger} from 'redux-logger';
import {composeWithDevTools} from 'redux-devtools-extension';
import {promiseMiddleware, localStorageMiddleware} from './middleware';
import reducer from './reducer';
const getMiddleware = () => {
if (process.env.NODE_ENV === 'production') {
return applyMiddleware(promiseMiddleware, localStorageMiddleware);
} else {
console.log('we are in devlopment mode');
return applyMiddleware(localStorageMiddleware, promiseMiddleware);
}
};
export const store = createStore(reducer, getMiddleware());
========= middleware =========
import agent from './agent';
import {ASYNC_START, ASYNC_END, LOGIN, LOGOUT, REGISTER, REFRESH_TOKEN} from './constants/actionTypes';
import AsyncStorage from '@react-native-community/async-storage';
const promiseMiddleware = store => next => action => {
console.log('promise middleware ');
console.log(store);
if (isPromise(action.payload)) {
store.dispatch({type: ASYNC_START, subtype: action.type});
const currentView = store.getState().viewChangeCounter;
const skipTracking = action.skipTracking;
action.payload.then(
res => {
const currentState = store.getState();
if (!skipTracking && currentState.viewChangeCounter !== currentView) {
return;
}
action.payload = res;
store.dispatch({type: ASYNC_END, promise: action.payload});
store.dispatch(action);
},
error => {
const currentState = store.getState();
if (!skipTracking && currentState.viewChangeCounter !== currentView) {
return;
}
action.error = true;
action.payload = error.response.body;
if (!action.skipTracking) {
store.dispatch({type: ASYNC_END, promise: action.payload});
}
store.dispatch(action);
},
);
return;
}
next(action);
};
const localStorageMiddleware = store => next => action => {
console.log('local storage middleware ');
console.log(store);
if (action.type === REGISTER || action.type === LOGIN) {
if (!action.error) {
AsyncStorage.setItem('jwt', action.payload.auth_token);
AsyncStorage.setItem('user', JSON.stringify(action.payload));
agent.setToken(action.payload.auth_token);
}
} else if (action.type === REFRESH_TOKEN) {
AsyncStorage.setItem('jwt', action.payload[0].auth_token);
} else if (action.type === LOGOUT) {
AsyncStorage.setItem('jwt', '');
agent.setToken(null);
}
next(action);
};
function isPromise(v) {
return v && typeof v.then === 'function';
}
export {promiseMiddleware, localStorageMiddleware};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment