12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- import thunk from 'redux-thunk'
- import {createStore, combineReducers,applyMiddleware } from 'redux';
- import { actionFindUser , actionSnippetFindByOwner} from '../actions';
- function promiseReducer(state , {type, name ,status , payload, error}) {
- if (!state){
- return {} //{status , payload , error}
- }
- if (type === 'PROMISE') {
- return {
- ...state,
- [name]: {status,payload , error}
- }
- }
- return state
- }
- function authReducer(state, action){ //....
- if (state === undefined){
- if (!localStorage.authToken){
- return {}
- }
- action.token = localStorage.authToken
- action.type = 'LOGIN'
- // добавить в action token из localStorage, и проимитировать LOGIN
- }
- if (action.type === 'LOGIN'){
- localStorage.authToken = action.token
- function jwt_decode (token) {
- var start64Url = token.split('.')[1]
- return JSON.parse(atob(start64Url))
- }
- return {token: action.token, payload: jwt_decode(action.token)}
- }
- if (action.type === 'LOGOUT'){
- localStorage.removeItem("authToken")
- //вернуть пустой объект
- return {}
- }
- return state
- }
- export const reducers = {
- promise:promiseReducer,
- auth:authReducer
- }
- export const store = createStore(combineReducers(reducers), applyMiddleware(thunk))
- const unsubscribe = store.subscribe(() => console.log('result here',store.getState()))
- if (localStorage.authToken) {
- store.dispatch(actionFindUser())
- store.dispatch(actionSnippetFindByOwner(store.getState().auth.payload.sub.id))
- }
- export default store
|