Skip to content

Commit eae36e4

Browse files
v0.2.0-beta.1
1 parent 2b15ac7 commit eae36e4

File tree

2 files changed

+41
-21
lines changed

2 files changed

+41
-21
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "emittor",
3-
"version": "0.1.0",
3+
"version": "0.2.0-beta.1",
44
"description": "State Management using custom hook without Wrapping components using Providers",
55
"private": false,
66
"repository": {

src/useEmittor.ts

Lines changed: 40 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,47 @@
11
"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";
44

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+
}
108

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;
1519
}
20+
return emittor.state;
21+
});
1622

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+
};
1927

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]);
2536

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

Comments
 (0)