Created
July 25, 2019 00:11
-
-
Save JavadocMD/4eaf835c6976e56f1bb2ac9d43b9ae72 to your computer and use it in GitHub Desktop.
TypeScript React/Redux Example
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
// user/store.ts | |
import * as Redux from 'redux' | |
import { anonymous, authenticated, User, UserData } from './User' | |
/* State */ | |
export interface State { | |
readonly user: User | |
} | |
export const defaultState: State = { user: anonymous } | |
/* Action */ | |
export interface LogIn { | |
readonly type: 'user/logIn' | |
readonly payload: UserData | |
} | |
export interface LogOut { | |
readonly type: 'user/logOut' | |
} | |
export type Action = LogIn | LogOut | |
export const reducer: Redux.Reducer<State, Action> = (state = defaultState, action) => { | |
switch (action.type) { | |
case 'user/logIn': | |
return { ...state, user: authenticated(action.payload) } | |
case 'user/logOut': | |
return { ...state, user: anonymous } | |
default: | |
return state | |
} | |
} | |
// store.ts | |
import { useSelector as genericUseSelector } from 'react-redux' | |
import * as Redux from 'redux' | |
import * as User from './user/store' | |
export interface State { | |
readonly user: User.State, | |
} | |
export type Action = User.Action | |
export type Store = Redux.Store<State, Action> | |
export type Dispatch = Redux.Dispatch<Action> | |
const rootReducer = Redux.combineReducers<State, Action>({ | |
user: User.reducer, | |
}) | |
export const defaultState: State = { | |
user: User.defaultState, | |
} | |
export const initializeStore = (initialState: State = defaultState) => Redux.createStore(rootReducer, initialState) | |
export const useSelector = <TSelected>( | |
selector: (state: State) => TSelected, | |
equalityFn?: (left: TSelected, right: TSelected) => boolean, | |
): TSelected => { | |
return genericUseSelector<State, TSelected>(selector, equalityFn) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment