Skip to content

Commit

Permalink
fix(reset): fixed reset would not properly modify values
Browse files Browse the repository at this point in the history
  • Loading branch information
BowlingX committed Dec 5, 2019
1 parent 393b10d commit 2a008c1
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 13 deletions.
3 changes: 2 additions & 1 deletion src/examples/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ const InnerApp = () => {
}

const DifferentApp = () => {
const { values: otherNsValues, pushState } = useAnotherQuery()
const { values: otherNsValues, pushState, resetPush } = useAnotherQuery()
return (
<>
<input
Expand All @@ -51,6 +51,7 @@ const DifferentApp = () => {
pushState(state => void (state.test = event.target.value))
}}
/>
<button onClick={() => resetPush()}>Reset</button>
</>
)
}
Expand Down
31 changes: 19 additions & 12 deletions src/lib/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,19 @@ export const converter = (historyInstance: History) => (set, get) => {
)
})
})

const reset = (ns: string, event: HistoryEventType) =>
set(
state =>
void Object.keys(state.values).forEach(key => {
if (state.initialValues[key] !== undefined) {
state.values[key] = state.initialValues[key]
}
}),
event,
ns
)

return {
/** batch pushes the given namespaces */
batchPushState: (ns: readonly string[], fn) => {
Expand Down Expand Up @@ -253,6 +266,10 @@ export const converter = (historyInstance: History) => (set, get) => {
state.subscribers = 1
state.unsubscribe = () => {
set(thisState => {
// it's possible that the state namespace has been cleared by the provider
if (!thisState[ns]) {
return
}
thisState[ns].subscribers = thisState[ns].subscribers - 1
if (thisState[ns].subscribers === 0) {
// tslint:disable-next-line:no-delete
Expand All @@ -278,18 +295,8 @@ export const converter = (historyInstance: History) => (set, get) => {
},
replaceState: (ns: string, fn) =>
set(state => fn(state.values), HistoryEventType.REPLACE, ns),
resetPush: (ns: string) =>
set(
state => void (state.values = state.initialValues),
HistoryEventType.PUSH,
ns
),
resetReplace: (ns: string) =>
set(
state => void (state.values = state.initialValues),
HistoryEventType.REPLACE,
ns
),
resetPush: (ns: string) => reset(ns, HistoryEventType.PUSH),
resetReplace: (ns: string) => reset(ns, HistoryEventType.REPLACE),
unregister: () => {
set(() => {
// return a new object for namespaces
Expand Down

0 comments on commit 2a008c1

Please sign in to comment.