refactor ChapterOptions (#126)
* Added a useLocalStorageReducer funtion This is mostly a refactor of ChapterOptions to simplify it with a reducer function Also moved a lot of function used in ChaperList to a utility file * Added UseCallback where needed * renamed utility folder to util to follow the convention throughout the app * Refactor: Moved Resume FAB to seperate file * Renamed Types and Function for chapter filtering and sorting with the chapterOption prefix * more renaming
This commit is contained in:
@@ -5,13 +5,24 @@
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
import React, { useState, Dispatch, SetStateAction } from 'react';
|
||||
import React, {
|
||||
useState,
|
||||
Dispatch,
|
||||
SetStateAction,
|
||||
useReducer,
|
||||
Reducer,
|
||||
} from 'react';
|
||||
import storage from './localStorage';
|
||||
|
||||
// eslint-disable-next-line max-len
|
||||
export default function useLocalStorage<T>(key: string, defaultValue: T | (() => T)) : [T, Dispatch<SetStateAction<T>>] {
|
||||
export default function useLocalStorage<T>(
|
||||
key: string,
|
||||
defaultValue: T | (() => T),
|
||||
): [T, Dispatch<SetStateAction<T>>] {
|
||||
const initialState = defaultValue instanceof Function ? defaultValue() : defaultValue;
|
||||
const [storedValue, setStoredValue] = useState<T>(storage.getItem(key, initialState));
|
||||
const [storedValue, setStoredValue] = useState<T>(
|
||||
storage.getItem(key, initialState),
|
||||
);
|
||||
|
||||
const setValue = ((value: T | ((prevState: T) => T)) => {
|
||||
// Allow value to be a function so we have same API as useState
|
||||
@@ -22,3 +33,16 @@ export default function useLocalStorage<T>(key: string, defaultValue: T | (() =>
|
||||
|
||||
return [storedValue, setValue];
|
||||
}
|
||||
|
||||
export function useReducerLocalStorage<S, A>(
|
||||
reducer: Reducer<S, A>,
|
||||
key: string,
|
||||
defaultState: S | (() => S),
|
||||
) {
|
||||
const [storedValue, setValue] = useLocalStorage(key, defaultState);
|
||||
return useReducer((state: S, action: A): S => {
|
||||
const newState = reducer(state, action);
|
||||
setValue(newState);
|
||||
return newState;
|
||||
}, storedValue);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user