Skip to content

Instantly share code, notes, and snippets.

@tgmarinho
Created June 11, 2021 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgmarinho/96779a4770777013b5289fad20ea4c83 to your computer and use it in GitHub Desktop.
Save tgmarinho/96779a4770777013b5289fad20ea4c83 to your computer and use it in GitHub Desktop.
UI Updater Reducer
import { ButtonAssetsAction } from "@/components/shared/AssetsAction";
import { useRouter } from "next/router";
import { createContext, useContext, useEffect, useReducer } from "react";
interface InitialStateType {
price?: string;
button?: ButtonAssetsAction[] | null;
owner: string;
updated?: boolean;
auction_bids?: number;
auction_buyer?: string;
aution_highestBid?: string;
}
const initialState: InitialStateType = {
price: "",
button: null,
owner: "",
updated: false,
auction_bids: 0,
auction_buyer: "",
aution_highestBid: "",
};
export enum Types {
SELL_SUCCESS,
BUY_SUCCESS,
CANCEL_SALE_SUCCESS,
CANCEL_AUCTION_SUCCESS,
PLACED_A_BID,
RESET,
}
export type Action = {
type: Types;
payload?: InitialStateType;
};
function reducer(state: InitialStateType, action: Action) {
switch (action.type) {
case Types.SELL_SUCCESS:
return { ...action.payload, updated: true };
case Types.CANCEL_SALE_SUCCESS:
return { ...action.payload, updated: true };
case Types.BUY_SUCCESS:
return { ...action.payload, updated: true };
case Types.CANCEL_AUCTION_SUCCESS:
return { ...action.payload, updated: true };
case Types.PLACED_A_BID:
return { ...action.payload, updated: true };
case Types.RESET:
return { ...initialState };
default:
return state;
}
}
interface OptimiscUpdaterData {
ui: InitialStateType;
dispatch: React.Dispatch<Action>;
}
const OptimiscUpdaterContext = createContext({} as OptimiscUpdaterData);
const OptimiscUpdaterProvider = ({ children }) => {
const [ui, dispatch] = useReducer(reducer, initialState);
const router = useRouter();
useEffect(() => {
dispatch({ type: Types.RESET });
}, [router?.query]);
return (
<OptimiscUpdaterContext.Provider value={{ ui, dispatch }}>
{children}
</OptimiscUpdaterContext.Provider>
);
};
// Optimisc UI Updater
function useUIUpdater() {
const context = useContext(OptimiscUpdaterContext);
if (!context) {
throw new Error(
"useOptimiscUpdater must be used within an OptimiscUpdaterProvider.",
);
}
return context;
}
export { OptimiscUpdaterProvider, useUIUpdater };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment