fix: routeState routes not updating if the key stays the same (#286)

This commit is contained in:
Victor Oliva 2022-11-15 10:55:57 +01:00 committed by GitHub
parent 8aefadfd72
commit afce5fa7c1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 61 additions and 6 deletions

View File

@ -186,5 +186,53 @@ describe("routeState", () => {
expect(a.getValue()).toEqual("a mapped a")
})
it("emits new values when the route stays the same", () => {
const root = createRoot()
const parentSource = new Subject<"a" | "b">()
const parent = substate(root, () => parentSource)
const [, { a }] = routeState(
parent,
{
a: (v) => "a mapped " + v,
},
() => "a",
)
root.run()
parentSource.next("a")
parentSource.next("b")
expect(a.getValue()).toEqual("a mapped b")
})
it("doesn't update if the value returns the same as before", () => {
const root = createRoot()
const parentSource = new Subject<"a" | "b">()
const parent = substate(root, () => parentSource)
const [, { a }] = routeState(
parent,
{
a: (v) => "a mapped " + v,
},
() => "a",
)
root.run()
const childSpy = jest.fn()
substate(a, () => {
childSpy()
return of("")
})
parentSource.next("a")
expect(childSpy).toHaveBeenCalledTimes(1)
parentSource.next("a")
expect(childSpy).toHaveBeenCalledTimes(1)
parentSource.next("b")
expect(childSpy).toHaveBeenCalledTimes(2)
})
})
})

View File

@ -37,11 +37,15 @@ export const routeState = <
): [StateNode<keyof O, K>, OT] => {
const internalParent = getInternals(parent)
const keys = new Set(Object.keys(routes))
const keyState = substate(parent, (ctx) => {
const key = selector(ctx(parent), ctx)
if (!keys.has(key)) throw new InvalidRouteError(key, [...keys])
return of(key)
})
const keyState = substate(
parent,
(ctx) => {
const key = selector(ctx(parent), ctx)
if (!keys.has(key)) throw new InvalidRouteError(key, [...keys])
return of(key)
},
() => false,
)
const routedState = mapRecord(routes, (mapper) => {
const result = detachedNode<any, any>(internalParent.keysOrder, (ctx) => {
@ -72,5 +76,8 @@ export const routeState = <
getInternals(keyState).childRunners.push(run)
return [keyState, mapRecord(routedState, (x) => x.public) as OT]
return [
substate(keyState, (ctx) => of(ctx(keyState))),
mapRecord(routedState, (x) => x.public) as OT,
]
}