Factor out useEventEmitterState hook
This commit is contained in:
parent
cdf0d98c3f
commit
b3a28bde89
2 changed files with 21 additions and 7 deletions
|
@ -117,12 +117,15 @@ const SpaceButton: React.FC<IButtonProps> = ({
|
||||||
};
|
};
|
||||||
|
|
||||||
const useSpaces = (): [Room[], Room[], Room | null] => {
|
const useSpaces = (): [Room[], Room[], Room | null] => {
|
||||||
const [invites, setInvites] = useState<Room[]>(SpaceStore.instance.invitedSpaces);
|
const invites = useEventEmitterState<Room[]>(SpaceStore.instance, UPDATE_INVITED_SPACES, () => {
|
||||||
useEventEmitter(SpaceStore.instance, UPDATE_INVITED_SPACES, setInvites);
|
return SpaceStore.instance.invitedSpaces;
|
||||||
const [spaces, setSpaces] = useState<Room[]>(SpaceStore.instance.spacePanelSpaces);
|
});
|
||||||
useEventEmitter(SpaceStore.instance, UPDATE_TOP_LEVEL_SPACES, setSpaces);
|
const spaces = useEventEmitterState<Room[]>(SpaceStore.instance, UPDATE_TOP_LEVEL_SPACES, () => {
|
||||||
const [activeSpace, setActiveSpace] = useState<Room>(SpaceStore.instance.activeSpace);
|
return SpaceStore.instance.spacePanelSpaces;
|
||||||
useEventEmitter(SpaceStore.instance, UPDATE_SELECTED_SPACE, setActiveSpace);
|
});
|
||||||
|
const activeSpace = useEventEmitterState<Room>(SpaceStore.instance, UPDATE_SELECTED_SPACE, () => {
|
||||||
|
return SpaceStore.instance.activeSpace;
|
||||||
|
});
|
||||||
return [invites, spaces, activeSpace];
|
return [invites, spaces, activeSpace];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
|
||||||
limitations under the License.
|
limitations under the License.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { useRef, useEffect } from "react";
|
import { useRef, useEffect, useState, useCallback } from "react";
|
||||||
import type { EventEmitter } from "events";
|
import type { EventEmitter } from "events";
|
||||||
|
|
||||||
type Handler = (...args: any[]) => void;
|
type Handler = (...args: any[]) => void;
|
||||||
|
@ -48,3 +48,14 @@ export const useEventEmitter = (emitter: EventEmitter, eventName: string | symbo
|
||||||
[eventName, emitter], // Re-run if eventName or emitter changes
|
[eventName, emitter], // Re-run if eventName or emitter changes
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type Mapper<T> = (...args: any[]) => T;
|
||||||
|
|
||||||
|
export const useEventEmitterState = <T>(emitter: EventEmitter, eventName: string | symbol, fn: Mapper<T>): T => {
|
||||||
|
const [value, setValue] = useState<T>(fn());
|
||||||
|
const handler = useCallback((...args: any[]) => {
|
||||||
|
setValue(fn(...args));
|
||||||
|
}, [fn]);
|
||||||
|
useEventEmitter(emitter, eventName, handler);
|
||||||
|
return value;
|
||||||
|
};
|
||||||
|
|
Loading…
Reference in a new issue