Skip to content

Commit

Permalink
refactor: useFetchData 바로 데이터를 리턴하도록 변경
Browse files Browse the repository at this point in the history
  • Loading branch information
nangkyeonglim committed May 20, 2023
1 parent 5852b44 commit b0a5aa8
Showing 1 changed file with 30 additions and 26 deletions.
56 changes: 30 additions & 26 deletions src/hooks/useFetchData.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,41 @@
import { useEffect, useState } from 'react';
import { useCallback, useState } from 'react';

const useFetchData = <ResponseData>(fetchUrl: string) => {
const [data, setData] = useState<ResponseData | null>(null);
type MethodType = 'POST' | 'PUT' | 'PATCH' | 'DELETE';

const useFetchData = () => {
const [loading, setLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState('');
const [error, setError] = useState<Error | null>(null);

useEffect(() => {
setLoading(true);
setErrorMessage('');
const fetchData = useCallback(async <bodyData>(url: string, methodType: MethodType, body?: bodyData) => {
try {
const response = await fetch(url, {
method: methodType,
body: JSON.stringify(body),
});

const fetchData = async () => {
try {
const response = await fetch(fetchUrl);
const responseData = await response.json();
setData(responseData);
} catch (error) {
if (error instanceof Error) {
setErrorMessage(error.message);
} else {
console.error(error);
}
} finally {
setLoading(false);
}
};
const responseData = await response.text();
const jsonData = responseData === '' ? {} : JSON.parse(responseData);

fetchData();
}, [fetchUrl]);
return {
data: jsonData,
headerData: response.headers,
};
} catch (error) {
if (error instanceof Error) {
setError(error);
} else {
console.error(error);
}
} finally {
setLoading(false);
setError(null);
}
}, []);

return {
data,
loading,
errorMessage,
error,
fetchData,
};
};

Expand Down

0 comments on commit b0a5aa8

Please sign in to comment.