diff --git a/package.json b/package.json index 0f0d113..6db4d10 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "emittor", - "version": "0.1.0", + "version": "0.2.0-beta.1", "description": "State Management using custom hook without Wrapping components using Providers", "private": false, "repository": { diff --git a/src/useEmittor.ts b/src/useEmittor.ts index c197484..c82ce46 100644 --- a/src/useEmittor.ts +++ b/src/useEmittor.ts @@ -1,27 +1,47 @@ "use client"; -import { useEffect, useRef, useState } from "react"; -import { Emittor } from './createEmittor'; +import { useEffect, useState } from "react"; +import { Emittor } from "./createEmittor"; -export const useEmittor = (emittor: Emittor): [T, ((state: T | ((state: T) => T)) => void)] => { - const [state, setState] = useState(emittor.state); - - const setValue = (state: T | ((state: T) => T)) => { - let newState = state as T +function isFunc(value: unknown): value is (state: T) => T { + return typeof value === "function"; +} - if (state instanceof Function) { - newState = state(emittor.state) - } - emittor.emit(newState) +export const useEmittor = ( + emittor: Emittor, + defaultValue?: T | (() => T) +): [T, (state: T | ((state: T) => T)) => void] => { + const [state, setState] = useState(() => { + // Initialize state with the emittor state or the default value + if (defaultValue !== undefined && emittor.state === undefined) { + const initial = isFunc(defaultValue) ? defaultValue() : defaultValue; + emittor.emit(initial); + return initial; } + return emittor.state; + }); - useEffect(() => { - emittor.connect(setState); + const setValue = (newState: T | ((state: T) => T)) => { + const updatedState = isFunc(newState) ? newState(state) : newState; + emittor.emit(updatedState); + }; - // Disconnect on unmount - return () => { - emittor.disconnect(setState); - }; - }, [emittor]); // Run effect again if emittor changes + // useEffect(() => { + // // Emit default value if the emittor state is undefined (only set in emit) + // if (defaultValue !== undefined && emittor.state === undefined) { + // console.log("defaultValue", defaultValue) + // const initial = isFunc(defaultValue) ? defaultValue() : defaultValue; + // emittor.emit(initial); + // } + // }, [defaultValue, emittor]); - return [state, setValue] -} + useEffect(() => { + const updateState = (newState: T) => setState(() => newState); + emittor.connect(updateState); + + return () => { + emittor.disconnect(updateState); + }; + }, [emittor]); + + return [state, setValue]; +};