fix: warning in console for PermField state
Massimo Melina committed
Feb 2, 2022 at 19:29 UTC
7badfd11287334f04351f213cb8a296ffb044bf2
2 files changed
+22
-4
admin/src/PermField.ts
+3
-3
@@ -1,12 +1,12 @@
1
-import { Dict } from './misc'
2
-import { createElement as h, Fragment, isValidElement, useState } from 'react'
1
+import { Dict, useStateMounted } from './misc'
2
+import { createElement as h, Fragment, isValidElement } from 'react'
3
import { Button, Grid } from '@mui/material'
4
import { Field, FieldProps, SelectField } from './Form'
5
import _ from 'lodash'
6
import { useApiComp } from './api'
7
8
export default function PermField({ label, value, onChange }: FieldProps<Dict<string> | null> & { keyLabel:string }) {
9
- const [temp, setTemp] = useState<string|undefined>()
9
+ const [temp, setTemp] = useStateMounted<string|undefined>(undefined)
10
const [res] = useApiComp('get_usernames')
11
const usernames = res.list
12
admin/src/misc.ts
+19
-1
@@ -1,4 +1,4 @@
1
-import { createElement as h, useRef } from 'react'
1
+import { createElement as h, useCallback, useEffect, useRef, useState } from 'react'
2
import { CircularProgress } from '@mui/material'
3
4
export type Dict<T = any> = Record<string, T>
@@ -64,3 +64,21 @@ export function enforceFinal(sub:string, s:string) {
64
export function isWindowsDrive(s?: string) {
65
return s && /^[a-zA-Z]:$/.test(s)
66
}
67
+
68
+export function useIsMounted() {
69
+ const mountRef = useRef(true)
70
+ useEffect(() => () => {
71
+ mountRef.current = false
72
+ }, [])
73
+ return useCallback(()=> mountRef.current, [mountRef])
74
+}
75
+
76
+export function useStateMounted<T>(init: T) {
77
+ const isMounted = useIsMounted()
78
+ const [v, set] = useState(init)
79
+ const setIfMounted = useCallback((x:T) => {
80
+ if (isMounted())
81
+ set(x)
82
+ }, [isMounted, set])
83
+ return [v, setIfMounted, isMounted] as [T, typeof setIfMounted, typeof isMounted]
84
+}