mirror of https://github.com/vector-im/riot-web
Factor out useEventEmitterState hook
parent
cdf0d98c3f
commit
b3a28bde89
|
@ -117,12 +117,15 @@ const SpaceButton: React.FC<IButtonProps> = ({
|
|||
};
|
||||
|
||||
const useSpaces = (): [Room[], Room[], Room | null] => {
|
||||
const [invites, setInvites] = useState<Room[]>(SpaceStore.instance.invitedSpaces);
|
||||
useEventEmitter(SpaceStore.instance, UPDATE_INVITED_SPACES, setInvites);
|
||||
const [spaces, setSpaces] = useState<Room[]>(SpaceStore.instance.spacePanelSpaces);
|
||||
useEventEmitter(SpaceStore.instance, UPDATE_TOP_LEVEL_SPACES, setSpaces);
|
||||
const [activeSpace, setActiveSpace] = useState<Room>(SpaceStore.instance.activeSpace);
|
||||
useEventEmitter(SpaceStore.instance, UPDATE_SELECTED_SPACE, setActiveSpace);
|
||||
const invites = useEventEmitterState<Room[]>(SpaceStore.instance, UPDATE_INVITED_SPACES, () => {
|
||||
return SpaceStore.instance.invitedSpaces;
|
||||
});
|
||||
const spaces = useEventEmitterState<Room[]>(SpaceStore.instance, UPDATE_TOP_LEVEL_SPACES, () => {
|
||||
return SpaceStore.instance.spacePanelSpaces;
|
||||
});
|
||||
const activeSpace = useEventEmitterState<Room>(SpaceStore.instance, UPDATE_SELECTED_SPACE, () => {
|
||||
return SpaceStore.instance.activeSpace;
|
||||
});
|
||||
return [invites, spaces, activeSpace];
|
||||
};
|
||||
|
||||
|
|
|
@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
|
|||
limitations under the License.
|
||||
*/
|
||||
|
||||
import { useRef, useEffect } from "react";
|
||||
import { useRef, useEffect, useState, useCallback } from "react";
|
||||
import type { EventEmitter } from "events";
|
||||
|
||||
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
|
||||
);
|
||||
};
|
||||
|
||||
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 New Issue