src/redux/track/reducer.ts

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.7 kB
1
Indexable
Never
import AsyncStorage from '@react-native-community/async-storage';
import {persistReducer} from 'redux-persist';

import * as Actions from './constants';
import * as TrackActionType from './type';
import {ActionType} from '../type';

const initState: TrackActionType.TrackState = {
  absoluteStartTrackDistanceMiles: 0,
  trackStation: [],
  trackSpeedLimit: [],
  trackGroupData: {},
  stopStations: {},
  trackLoading: false,
  trackTotalLength: 0,
  nearestTrack: null,
};

const TrackReducer = (
  state: TrackActionType.TrackState = initState,
  action: ActionType = {
    type: '',
    payload: {},
  },
) => {
  switch (action.type) {
    case Actions.TOGGLE_TRACK_LOADING:
      return {
        ...state,
        trackLoading: action.payload,
      };
    case Actions.SET_TRACK_TOTAL_LENGTH:
      return {...state, trackTotalLength: action.payload};
    case Actions.CLEAR_STOP_STATION:
      return {...state, stopStations: {}};
    case Actions.SET_STOP_STATION:
      return {
        ...state,
        stopStations: {
          ...state.stopStations,
          [action.payload.key]: action.payload,
        },
      };
    case Actions.GET_TRACK_DATA_SUCCESS:
      return {
        ...state,
        absoluteStartTrackDistanceMiles:
          action.payload.absoluteStartTrackDistanceMiles,
        trackGroupData: action.payload,
      };
    case Actions.GET_TRACK_DATA_FAIL:
      return {
        ...state,
        trackGroupData: {
          ...state.trackGroupData,
          [action.payload.key]: {
            ...action.payload,
            data: {
              ...action.payload.data,
              trackStation: action.payload.data.trackStation,
              corridors: action.payload.data.corridors,
              trackSpeedLimit: action.payload.data.trackSpeedLimit,
            },
          },
        },
      };
    case Actions.GET_NEAREST_TRACK_SUCCESS:
      return {
        ...state,
        nearestTrack: action.payload,
      };
    case Actions.GET_NEAREST_TRACK_FAIL:
      return {
        ...state,
        nearestTrack: null,
      };
    case Actions.CLEAR_TRACK_REDUX_EXCEPT_NEAREST_TRACK:
      return {
        ...state,
        absoluteStartTrackDistanceMiles: 0,
        trackStation: [],
        trackSpeedLimit: [],
        trackGroupData: {},
        stopStations: {},
        trackLoading: false,
        trackTotalLength: 0,
      };
    default:
      return state;
  }
};

const persistConfig = {
  key: 'track',
  storage: AsyncStorage,
  whitelist: [
    'absoluteStartTrackDistanceMiles',
    'trackStation',
    'trackSpeedLimit',
    'trackTotalLength',
  ],
  blacklist: ['stopStations', 'trackGroupData'],
};

export default persistReducer(persistConfig, TrackReducer);