admin: fix: state warning in console
Massimo Melina committed
Feb 4, 2022 at 09:46 UTC
7a1e5c0971a8e0bb77ed861647d2866bf5633f27
2 files changed
+10
-10
admin/src/api.ts
+8
-8
@@ -1,5 +1,5 @@
1
-import { createElement as h, useEffect, useMemo, useState } from 'react'
2
-import { Dict, Falsy, getCookie, spinner } from './misc'
1
+import { createElement as h, useEffect, useMemo } from 'react'
2
+import { Dict, Falsy, getCookie, spinner, useStateMounted } from './misc'
3
import { Alert } from '@mui/material'
4
5
export function useApiComp(...args: any[]): ReturnType<typeof useApi> {
@@ -41,9 +41,9 @@ export class ApiError extends Error {
41
}
42
43
export function useApi(cmd: string | Falsy, params?: object) : [any, ()=>void] {
44
- const [ret, setRet] = useState()
45
- const [forcer, setForcer] = useState(0)
46
- const [state] = useState({ loading: false })
44
+ const [ret, setRet] = useStateMounted(undefined)
45
+ const [forcer, setForcer] = useStateMounted(0)
46
+ const [state] = useStateMounted({ loading: false })
47
useEffect(()=>{
48
setRet(undefined)
49
if (!cmd) return
@@ -86,9 +86,9 @@ function addCsrf(params?: Dict) {
86
}
87
88
export function useApiEvents<Record>(cmd:string|Falsy, params: Dict={}) {
89
- const [list, setList] = useState<Record[]>([])
90
- const [error, setError] = useState<any>()
91
- const [loading, setLoading] = useState(false)
89
+ const [list, setList] = useStateMounted<Record[]>([])
90
+ const [error, setError] = useStateMounted<any>(undefined)
91
+ const [loading, setLoading] = useStateMounted(false)
92
useEffect(() => {
93
if (!cmd) return
94
const buffer: Record[] = []
admin/src/misc.ts
+2
-2
@@ -76,9 +76,9 @@ export function useIsMounted() {
76
export function useStateMounted<T>(init: T) {
77
const isMounted = useIsMounted()
78
const [v, set] = useState(init)
79
- const setIfMounted = useCallback((x:T) => {
79
+ const setIfMounted = useCallback((newValue:T | ((previous:T)=>T)) => {
80
if (isMounted())
81
- set(x)
81
+ set(newValue)
82
}, [isMounted, set])
83
return [v, setIfMounted, isMounted] as [T, typeof setIfMounted, typeof isMounted]
84
}