Implement redux.

This commit is contained in:
Mike Cao 2020-08-04 22:45:05 -07:00
parent 9d8a2406e1
commit 5d4ff5cfa4
31 changed files with 341 additions and 85 deletions

16
redux/actions/user.js Normal file
View file

@ -0,0 +1,16 @@
import { createSlice } from '@reduxjs/toolkit';
const user = createSlice({
name: 'user',
initialState: null,
reducers: {
updateUser(state, action) {
state = action.payload;
return state;
},
},
});
export const { updateUser } = user.actions;
export default user.reducer;

4
redux/reducers.js Normal file
View file

@ -0,0 +1,4 @@
import { combineReducers } from 'redux';
import user from './actions/user';
export default combineReducers({ user });

40
redux/store.js Normal file
View file

@ -0,0 +1,40 @@
import { useMemo } from 'react';
import { configureStore } from '@reduxjs/toolkit';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
let store;
export function getStore(preloadedState) {
return configureStore({
reducer: rootReducer,
middleware: [thunk],
preloadedState,
});
}
export const initializeStore = preloadedState => {
let _store = store ?? getStore(preloadedState);
// After navigating to a page with an initial Redux state, merge that state
// with the current state in the store, and create a new store
if (preloadedState && store) {
_store = getStore({
...store.getState(),
...preloadedState,
});
// Reset the current store
store = undefined;
}
// For SSG and SSR always create a new store
if (typeof window === 'undefined') return _store;
// Create the store once in the client
if (!store) store = _store;
return _store;
};
export function useStore(initialState) {
return useMemo(() => initializeStore(initialState), [initialState]);
}