|
| 1 | +import raf from '../../_util/raf'; |
1 | 2 | import type { Ref, UnwrapRef } from 'vue';
|
2 |
| -import { onBeforeUnmount, ref } from 'vue'; |
| 3 | +import { onBeforeUnmount, ref, shallowRef } from 'vue'; |
3 | 4 |
|
4 | 5 | export type Updater<State> = (prev: State) => State;
|
5 | 6 |
|
6 |
| -/** |
7 |
| - * Execute code before next frame but async |
8 |
| - */ |
9 | 7 | export function useLayoutState<State>(
|
10 | 8 | defaultState: State,
|
11 | 9 | ): [Ref<State>, (updater: Updater<State>) => void] {
|
12 |
| - const stateRef = ref<State>(defaultState); |
13 |
| - // const [, forceUpdate] = useState({}); |
14 |
| - |
15 |
| - const lastPromiseRef = ref<Promise<void>>(null); |
16 |
| - const updateBatchRef = ref<Updater<State>[]>([]); |
| 10 | + const stateRef = shallowRef<State>(defaultState); |
| 11 | + let rafId: number; |
| 12 | + const updateBatchRef = shallowRef<Updater<State>[]>([]); |
17 | 13 | function setFrameState(updater: Updater<State>) {
|
18 | 14 | updateBatchRef.value.push(updater);
|
19 |
| - |
20 |
| - const promise = Promise.resolve(); |
21 |
| - lastPromiseRef.value = promise; |
22 |
| - |
23 |
| - promise.then(() => { |
24 |
| - if (lastPromiseRef.value === promise) { |
25 |
| - const prevBatch = updateBatchRef.value; |
26 |
| - // const prevState = stateRef.value; |
27 |
| - updateBatchRef.value = []; |
28 |
| - |
29 |
| - prevBatch.forEach(batchUpdater => { |
30 |
| - stateRef.value = batchUpdater(stateRef.value as State) as UnwrapRef<State>; |
31 |
| - }); |
32 |
| - |
33 |
| - lastPromiseRef.value = null; |
34 |
| - } |
| 15 | + raf.cancel(rafId); |
| 16 | + rafId = raf(() => { |
| 17 | + const prevBatch = updateBatchRef.value; |
| 18 | + // const prevState = stateRef.value; |
| 19 | + updateBatchRef.value = []; |
| 20 | + prevBatch.forEach(batchUpdater => { |
| 21 | + stateRef.value = batchUpdater(stateRef.value as State); |
| 22 | + }); |
35 | 23 | });
|
36 | 24 | }
|
37 | 25 | onBeforeUnmount(() => {
|
38 |
| - lastPromiseRef.value = null; |
| 26 | + raf.cancel(rafId); |
39 | 27 | });
|
40 | 28 |
|
41 | 29 | return [stateRef as Ref<State>, setFrameState];
|
|
0 commit comments