* Creates snapshot getters that share equal selected results across renders. * A new getter is created on each render. Each getter caches its snapshot until the matching mutations * or their states change. * @returns A factory for snapshot getters with a shared result cache.
()
| 67 | * @returns A factory for snapshot getters with a shared result cache. |
| 68 | */ |
| 69 | function createSnapshotFactory< |
| 70 | TResult = MutationState, |
| 71 | TMutation extends Mutation<any, any, any, any> = |
| 72 | MutationTypeFromResult<TResult>, |
| 73 | >() { |
| 74 | let previousResult: Array<TResult> | undefined |
| 75 | |
| 76 | return ( |
| 77 | mutationCache: MutationCache, |
| 78 | options: MutationStateOptions<TResult, TMutation>, |
| 79 | ) => { |
| 80 | let inputs: Array<unknown> = [] |
| 81 | let snapshot: Array<TResult> | undefined |
| 82 | |
| 83 | return (): Array<TResult> => { |
| 84 | const mutations = mutationCache.findAll(options.filters) |
| 85 | const nextInputs = mutations.flatMap((mutation) => [ |
| 86 | mutation, |
| 87 | mutation.state, |
| 88 | ]) |
| 89 | |
| 90 | if ( |
| 91 | !snapshot || |
| 92 | nextInputs.length !== inputs.length || |
| 93 | nextInputs.some((input, index) => !Object.is(input, inputs[index])) |
| 94 | ) { |
| 95 | inputs = nextInputs |
| 96 | snapshot = replaceEqualDeep( |
| 97 | previousResult, |
| 98 | mutations.map( |
| 99 | (mutation): TResult => |
| 100 | (options.select |
| 101 | ? options.select(mutation as TMutation) |
| 102 | : mutation.state) as TResult, |
| 103 | ), |
| 104 | ) |
| 105 | previousResult = snapshot |
| 106 | } |
| 107 | |
| 108 | return snapshot |
| 109 | } |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | /** |
| 114 | * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass |
no test coverage detected