Created
June 11, 2021 16:23
-
-
Save tgmarinho/96779a4770777013b5289fad20ea4c83 to your computer and use it in GitHub Desktop.
UI Updater Reducer
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
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