-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.tsx
56 lines (48 loc) · 1.88 KB
/
App.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import React, { useEffect, useState } from "react"
import useSafeAsyncMount from '../../src';
export default function App() {
const [isShowingChild, setIsShowingChild] = useState<boolean>(true)
return (
<div>
<button onClick={() => setIsShowingChild(prev => !prev)}>{isShowingChild ? "Hide" : "Show"} Child</button>
<small> (The optional cleanup function's output is available in console)</small>
{isShowingChild && <Example />}
</div>
)
}
function Example() {
const [componentStateStr, setComponentStateStr] = useState<string>("Component mounted, safe mount hook has NOT finished");
const { SafeRender, safeState } = useSafeAsyncMount(async isActive => {
await new Promise((resolve) => setTimeout(resolve, 2000));
if (isActive()) {
// ^ This avoids setting component state after unmount
// These values are defined and type-safe in the `SafeRender` component
return {
stateOne: "Some value my component depends on",
stateTwo: Math.random()
}
}
}, console.log)
useEffect(() => {
// Optional
if (safeState) {
setComponentStateStr("Component mounted, safe mount hook has finished!")
}
}, [safeState])
return (
<>
<h1>{componentStateStr}</h1>
<SafeRender>
{({ stateOne, stateTwo }) => (
<>
<h2>I can be sure that the the variables "<em>stateOne</em>" and "<em>stateTwo</em>" are defined and type-safe!</h2>
<br />
<code>stateOne: "{stateOne}"</code>
<br />
<code>stateTwo: "{stateTwo}"</code>
</>
)}
</SafeRender>
</>
)
}