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
Raw Normal View History

2020-09-29 08:52:39 +00:00
import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { addLayer, removeLayer, showLayer, hideLayer } from "~store/ui/reducer";
2020-09-29 09:31:55 +00:00
import { UILayer } from "~store/ui/state";
2020-09-29 08:52:39 +00:00
export default function useUILayer(data: UILayer, show: boolean) {
const dispatch = useDispatch();
2020-09-29 09:31:55 +00:00
const [id] = useState(data.type + "-" + Math.random().toString(32).slice(2));
2020-09-29 08:52:39 +00:00
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;
}