|
1 | 1 | "use client";
|
2 |
| -import { useEffect, useRef, useState } from "react"; |
3 |
| -import { Emittor } from './createEmittor'; |
| 2 | +import { useEffect, useState } from "react"; |
| 3 | +import { Emittor } from "./createEmittor"; |
4 | 4 |
|
5 |
| -export const useEmittor = <T>(emittor: Emittor<T>): [T, ((state: T | ((state: T) => T)) => void)] => { |
6 |
| - const [state, setState] = useState(emittor.state); |
7 |
| - |
8 |
| - const setValue = (state: T | ((state: T) => T)) => { |
9 |
| - let newState = state as T |
| 5 | +function isFunc<T>(value: unknown): value is (state: T) => T { |
| 6 | + return typeof value === "function"; |
| 7 | +} |
10 | 8 |
|
11 |
| - if (state instanceof Function) { |
12 |
| - newState = state(emittor.state) |
13 |
| - } |
14 |
| - emittor.emit(newState) |
| 9 | +export const useEmittor = <T>( |
| 10 | + emittor: Emittor<T>, |
| 11 | + defaultValue?: T | (() => T) |
| 12 | +): [T, (state: T | ((state: T) => T)) => void] => { |
| 13 | + const [state, setState] = useState<T>(() => { |
| 14 | + // Initialize state with the emittor state or the default value |
| 15 | + if (defaultValue !== undefined && emittor.state === undefined) { |
| 16 | + const initial = isFunc<T>(defaultValue) ? defaultValue() : defaultValue; |
| 17 | + emittor.emit(initial); |
| 18 | + return initial; |
15 | 19 | }
|
| 20 | + return emittor.state; |
| 21 | + }); |
16 | 22 |
|
17 |
| - useEffect(() => { |
18 |
| - emittor.connect(setState); |
| 23 | + const setValue = (newState: T | ((state: T) => T)) => { |
| 24 | + const updatedState = isFunc<T>(newState) ? newState(state) : newState; |
| 25 | + emittor.emit(updatedState); |
| 26 | + }; |
19 | 27 |
|
20 |
| - // Disconnect on unmount |
21 |
| - return () => { |
22 |
| - emittor.disconnect(setState); |
23 |
| - }; |
24 |
| - }, [emittor]); // Run effect again if emittor changes |
| 28 | + // useEffect(() => { |
| 29 | + // // Emit default value if the emittor state is undefined (only set in emit) |
| 30 | + // if (defaultValue !== undefined && emittor.state === undefined) { |
| 31 | + // console.log("defaultValue", defaultValue) |
| 32 | + // const initial = isFunc<T>(defaultValue) ? defaultValue() : defaultValue; |
| 33 | + // emittor.emit(initial); |
| 34 | + // } |
| 35 | + // }, [defaultValue, emittor]); |
25 | 36 |
|
26 |
| - return [state, setValue] |
27 |
| -} |
| 37 | + useEffect(() => { |
| 38 | + const updateState = (newState: T) => setState(() => newState); |
| 39 | + emittor.connect(updateState); |
| 40 | + |
| 41 | + return () => { |
| 42 | + emittor.disconnect(updateState); |
| 43 | + }; |
| 44 | + }, [emittor]); |
| 45 | + |
| 46 | + return [state, setValue]; |
| 47 | +}; |
0 commit comments