MCPcopy Index your code
hub / github.com/ampproject/amphtml / useQuery

Function useQuery

src/preact/hooks/useQuery.ts:67–118  ·  view source on GitHub ↗
(
  queryFn: () => Promise<TData>,
  {
    enabled,
    initialData,
    onError = noop,
    onSettled = noop,
    onSuccess = noop,
  }: QueryConfig<TData>
)

Source from the content-addressed store, hash-verified

65 * )
66 */
67export function useQuery<TData>(
68 queryFn: () => Promise<TData>,
69 {
70 enabled,
71 initialData,
72 onError = noop,
73 onSettled = noop,
74 onSuccess = noop,
75 }: QueryConfig<TData>
76) {
77 const [state, setState] = useStateSafe<QueryState<TData>>({
78 ...DEFAULT_STATE_VALUES,
79 data: initialData,
80 });
81
82 // This ref ensures that the fetch function is not called more than once with the same props.
83 const ref = useValueRef({
84 initialData,
85 onSettled,
86 onError,
87 onSuccess,
88 state,
89 queryFn,
90 });
91
92 const fetchQueryData = useCallback(() => {
93 const {onError, onSettled, onSuccess, queryFn, state} = ref.current!;
94 setState((s) => ({...s, error: null, loading: true}));
95 // This function intentionally does not use async/await in order to avoid
96 // issues with regenerator-runtime in bento components.
97 queryFn().then(
98 (data) => {
99 setState((s) => ({...s, error: null, loading: false, data}));
100 onSuccess(data);
101 onSettled(state.data, state.error);
102 },
103 (error) => {
104 setState((s) => ({...s, data: null, loading: false, error}));
105 onError(error);
106 onSettled(state.data, state.error);
107 }
108 );
109 }, [ref, setState]);
110
111 useEffect(() => {
112 if (enabled) {
113 fetchQueryData();
114 }
115 }, [enabled, fetchQueryData]);
116
117 return {...state, refetch: fetchQueryData};
118}

Callers 1

BentoAutocompleteFunction · 0.90

Calls 4

useStateSafeFunction · 0.90
useValueRefFunction · 0.90
onErrorFunction · 0.85
thenMethod · 0.45

Tested by

no test coverage detected