This repository has been archived on 2020-09-30. You can view files and clone it, but cannot push or open issues or pull requests.
odyfive/src/ui/utils/useLayer.ts

33 lines
789 B
TypeScript

import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { addLayer, removeLayer, showLayer, hideLayer } from "~store/ui/reducer";
import { UILayer } from "~store/ui/state";
export default function useUILayer(data: UILayer, show: boolean) {
const dispatch = useDispatch();
const [id] = useState(data.type + "-" + Math.random().toString(32).slice(2));
const [visible, setVisible] = useState(show);
useEffect(() => {
dispatch(addLayer({ id, data }));
return () => {
dispatch(removeLayer({ id }));
};
}, []);
useEffect(() => {
if (visible) {
dispatch(showLayer({ id }));
} else {
dispatch(hideLayer({ id }));
}
}, [visible]);
if (show != visible) {
setVisible(show);
}
return id;
}