Open History to see the last commit
1// @ts-nocheck
2β
3import React from 'react'
4β
5import { useTheme } from './theme'
6import useMediaQuery from './useMediaQuery'
7β
8export const isServer = typeof window === 'undefined'
9β
10export function isStale(query) {
11 return typeof query.isStale === 'function'
12 ? query.isStale()
13 : query.state.isStale
14}
15β
16export function getQueryStatusColor(query, theme) {
17 return query.state.isFetching
18 ? theme.active
19 : isStale(query)
20 ? theme.warning
21 : !query.observers.length
22 ? theme.gray
23 : theme.success
24}
25β
26export function getQueryStatusLabel(query) {
27 return query.state.isFetching
28 ? 'fetching'
29 : !query.observers.length
30 ? 'inactive'
31 : isStale(query)
32 ? 'stale'
33 : 'fresh'
34}
35β
36export function styled(type, newStyles, queries = {}) {
37 return React.forwardRef(({ style, ...rest }, ref) => {
38 const theme = useTheme()
39β
40 const mediaStyles = Object.entries(queries).reduce(
41 (current, [key, value]) => {
42 // eslint-disable-next-line react-hooks/rules-of-hooks
43 return useMediaQuery(key)
44 ? {
45 ...current,
46 ...(typeof value === 'function' ? value(rest, theme) : value),
47 }
48 : current
49 },
50 {}
51 )
52β
53 return React.createElement(type, {
54 ...rest,
55 style: {
56 ...(typeof newStyles === 'function'
57 ? newStyles(rest, theme)
58 : newStyles),
59 ...style,
60 ...mediaStyles,
61 },
62 ref,
63 })
64 })
65}
66β
67function useIsMounted() {
68 const mountedRef = React.useRef(false)
69 const isMounted = React.useCallback(() => mountedRef.current, [])
70β
71 React[isServer ? 'useEffect' : 'useLayoutEffect'](() => {
72 mountedRef.current = true
73 return () => {
74 mountedRef.current = false
75 }
76 }, [])
77β
78 return isMounted
79}
80β
81/**
82 * This hook is a safe useState version which schedules state updates in microtasks
83 * to prevent updating a component state while React is rendering different components
84 * or when the component is not mounted anymore.
85 */
86export function useSafeState(initialState) {
87 const isMounted = useIsMounted()
88 const [state, setState] = React.useState(initialState)
89β
90 const safeSetState = React.useCallback(
91 value => {
92 scheduleMicrotask(() => {
93 if (isMounted()) {
94 setState(value)
95 }
96 })
97 },
98 [isMounted]
99 )
100β
101 return [state, safeSetState]
102}
103β
104/**
105 * Schedules a microtask.
106 * This can be useful to schedule state updates after rendering.
107 */
108function scheduleMicrotask(callback) {
109 Promise.resolve()
110 .then(callback)
111 .catch(error =>
112 setTimeout(() => {
113 throw error
114 })
115 )
116}