Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

refactor: migrate Loader to React Hooks (#733)

Guilherme Oenningd085b35ad56f
diff --git a/public/components/common/Loader.tsx b/public/components/common/Loader.tsx
index 62189ddc7..ce0beb2dd 100644
--- a/public/components/common/Loader.tsx
+++ b/public/components/common/Loader.tsx
@@ -1,35 +1,14 @@
import "./Loader.scss";
-import React from "react";
+import React, { useState } from "react";
+import { useTimeout } from "@fider/hooks";
-interface LoaderState {
- show: boolean;
-}
-
-export class Loader extends React.Component<{}, LoaderState> {
- private unmounted: boolean;
- constructor(props: {}) {
- super(props);
- this.unmounted = false;
- this.state = {
- show: false
- };
- }
+export function Loader() {
+ const [show, setShow] = useState(false);
- public componentDidMount() {
- setTimeout(() => {
- if (!this.unmounted) {
- this.setState({
- show: true
- });
- }
- }, 500);
- }
- public componentWillUnmount() {
- this.unmounted = true;
- }
+ useTimeout(() => {
+ setShow(true);
+ }, 500);
- public render() {
- return this.state.show && <div className="c-loader" />;
- }
+ return show ? <div className="c-loader" /> : null;
}
diff --git a/public/hooks/index.ts b/public/hooks/index.ts
index 6bbdf7bdf..c5f46f3bc 100644
--- a/public/hooks/index.ts
+++ b/public/hooks/index.ts
@@ -1 +1,2 @@
+export * from "./use-timeout";
export * from "./use-fider";
diff --git a/public/hooks/use-timeout.ts b/public/hooks/use-timeout.ts
new file mode 100644
index 000000000..95ba79bdb
--- /dev/null
+++ b/public/hooks/use-timeout.ts
@@ -0,0 +1,23 @@
+import { useRef, useEffect } from "react";
+
+type CallbackFunction = () => void;
+
+export function useTimeout(callback: CallbackFunction, delay: number) {
+ const savedCallback = useRef<CallbackFunction>();
+
+ useEffect(() => {
+ savedCallback.current = callback;
+ });
+
+ useEffect(() => {
+ function tick() {
+ if (savedCallback.current) {
+ savedCallback.current();
+ }
+ }
+ const timer = window.setTimeout(tick, delay);
+ return function cleanup() {
+ window.clearTimeout(timer);
+ };
+ }, [delay]);
+}