mirror of
https://github.com/logto-io/logto.git
synced 2025-01-27 21:39:16 -05:00
fix(ui): fix useApi request in useEffect dead loop bug (#158)
wrap the request method in userApi hook into a useCallback
This commit is contained in:
parent
dd7a385363
commit
3a80d99c9f
1 changed files with 21 additions and 18 deletions
|
@ -1,6 +1,6 @@
|
||||||
import { RequestErrorBody } from '@logto/schemas';
|
import { RequestErrorBody } from '@logto/schemas';
|
||||||
import { HTTPError } from 'ky';
|
import { HTTPError } from 'ky';
|
||||||
import { useState } from 'react';
|
import { useState, useCallback } from 'react';
|
||||||
|
|
||||||
type UseApi<T extends any[], U> = {
|
type UseApi<T extends any[], U> = {
|
||||||
result?: U;
|
result?: U;
|
||||||
|
@ -16,26 +16,29 @@ function useApi<Args extends any[], Response>(
|
||||||
const [error, setError] = useState<RequestErrorBody | null>(null);
|
const [error, setError] = useState<RequestErrorBody | null>(null);
|
||||||
const [result, setResult] = useState<Response>();
|
const [result, setResult] = useState<Response>();
|
||||||
|
|
||||||
const run = async (...args: Args) => {
|
const run = useCallback(
|
||||||
setLoading(true);
|
async (...args: Args) => {
|
||||||
setError(null);
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await api(...args);
|
const result = await api(...args);
|
||||||
setResult(result);
|
setResult(result);
|
||||||
setLoading(false);
|
|
||||||
} catch (error: unknown) {
|
|
||||||
if (error instanceof HTTPError) {
|
|
||||||
const kyError = await error.response.json<RequestErrorBody>();
|
|
||||||
setError(kyError);
|
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
return;
|
} catch (error: unknown) {
|
||||||
}
|
if (error instanceof HTTPError) {
|
||||||
|
const kyError = await error.response.json<RequestErrorBody>();
|
||||||
|
setError(kyError);
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
},
|
||||||
|
[api]
|
||||||
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
loading,
|
loading,
|
||||||
|
|
Loading…
Add table
Reference in a new issue