(
table: string,
config: UseSelectConfig<Data> = { columns: '*', options: {} },
)
| 33 | } |
| 34 | |
| 35 | export function useSelect<Data = any>( |
| 36 | table: string, |
| 37 | config: UseSelectConfig<Data> = { columns: '*', options: {} }, |
| 38 | ): UseSelectResponse<Data> { |
| 39 | const client = useClient() |
| 40 | const isMounted = useRef(false) |
| 41 | const [state, setState] = useState<UseSelectState>({ |
| 42 | ...initialState, |
| 43 | stale: false, |
| 44 | }) |
| 45 | |
| 46 | const execute = useCallback(async () => { |
| 47 | if (config.pause) return null |
| 48 | setState((x) => ({ |
| 49 | ...initialState, |
| 50 | data: x.data, |
| 51 | stale: true, |
| 52 | fetching: true, |
| 53 | })) |
| 54 | const source = client |
| 55 | .from<Data>(table) |
| 56 | .select(config.columns, config.options) |
| 57 | const { count, data, error } = await (config.filter |
| 58 | ? config.filter(source) |
| 59 | : source) |
| 60 | const res = { count, data, error } |
| 61 | if (isMounted.current) |
| 62 | setState({ ...res, stale: false, fetching: false }) |
| 63 | return res |
| 64 | }, [client, config, table]) |
| 65 | |
| 66 | /* eslint-disable react-hooks/exhaustive-deps */ |
| 67 | useEffect(() => { |
| 68 | isMounted.current = true |
| 69 | execute() |
| 70 | return () => { |
| 71 | isMounted.current = false |
| 72 | } |
| 73 | }, [config?.filter]) |
| 74 | /* eslint-enable react-hooks/exhaustive-deps */ |
| 75 | |
| 76 | return [state, execute] |
| 77 | } |
no test coverage detected