|
| 1 | +import * as api from './api' |
| 2 | +import { Observable } from './rxjs-library' |
| 3 | + |
| 4 | +const FETCH_CHARACTER_SUCCESS = 'FETCH_CHARACTER_SUCCESS' |
| 5 | +const FETCH_CHARACTER_FAILURE = 'FETCH_CHARACTER_FAILURE' |
| 6 | +const START_FETCHING_CHARACTERS = 'START_FETCHING_CHARACTERS' |
| 7 | +const STOP_FETCHING_CHARACTERS = 'STOP_FETCHING_CHARACTERS' |
| 8 | + |
| 9 | +const INITIAL_STATE = { |
| 10 | + nextCharacterId: 1, |
| 11 | + character: {}, |
| 12 | + isFetchedOnServer: false, |
| 13 | + error: null |
| 14 | +} |
| 15 | + |
| 16 | +export default function reducer (state = INITIAL_STATE, { type, payload }) { |
| 17 | + switch (type) { |
| 18 | + case FETCH_CHARACTER_SUCCESS: |
| 19 | + return { |
| 20 | + ...state, |
| 21 | + character: payload.response, |
| 22 | + isFetchedOnServer: payload.isServer, |
| 23 | + nextCharacterId: state.nextCharacterId + 1 |
| 24 | + } |
| 25 | + case FETCH_CHARACTER_FAILURE: |
| 26 | + return { ...state, error: payload.error, isFetchedOnServer: payload.isServer } |
| 27 | + default: |
| 28 | + return state |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +export const startFetchingCharacters = () => ({ type: START_FETCHING_CHARACTERS }) |
| 33 | +export const stopFetchingCharacters = () => ({ type: STOP_FETCHING_CHARACTERS }) |
| 34 | + |
| 35 | +export const fetchUserEpic = (action$, store) => |
| 36 | + action$.ofType(START_FETCHING_CHARACTERS) |
| 37 | + .mergeMap( |
| 38 | + action => Observable.interval(3000) |
| 39 | + .mergeMap(x => api.fetchCharacter(store.getState().nextCharacterId)) |
| 40 | + .takeUntil(action$.ofType(STOP_FETCHING_CHARACTERS)) |
| 41 | + ) |
| 42 | + |
| 43 | +export const fetchCharacterSuccess = (response, isServer) => ({ |
| 44 | + type: FETCH_CHARACTER_SUCCESS, |
| 45 | + payload: { response, isServer } |
| 46 | +}) |
| 47 | + |
| 48 | +export const fetchCharacterFailure = (error, isServer) => ({ |
| 49 | + type: FETCH_CHARACTER_FAILURE, |
| 50 | + payload: { error, isServer } |
| 51 | +}) |
0 commit comments