Skip to content

Commit

Permalink
v0.2.0-beta.1
Browse files Browse the repository at this point in the history
  • Loading branch information
programming-with-ia committed Oct 30, 2024
1 parent 2b15ac7 commit eae36e4
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 21 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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": {
Expand Down
60 changes: 40 additions & 20 deletions src/useEmittor.ts
Original file line number Diff line number Diff line change
@@ -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 = <T>(emittor: Emittor<T>): [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<T>(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 = <T>(
emittor: Emittor<T>,
defaultValue?: T | (() => T)
): [T, (state: T | ((state: T) => T)) => void] => {
const [state, setState] = useState<T>(() => {
// Initialize state with the emittor state or the default value
if (defaultValue !== undefined && emittor.state === undefined) {
const initial = isFunc<T>(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<T>(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<T>(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];
};

0 comments on commit eae36e4

Please sign in to comment.