import React, {
useState,
useEffect
} from
'react'
;
function
useAsyncOperation(url) {
const [data, setData] = useState(
null
);
const [isLoading, setIsLoading] = useState(
false
);
const [error, setError] = useState(
null
);
useEffect(() => {
const fetchData = async () => {
setIsLoading(
true
);
try
{
const response = await fetch(url);
if
(!response.ok) {
throw
new
Error(
'Network response was not ok'
);
}
const result = await response.json();
setData(result);
}
catch
(error) {
setError(error);
} finally {
setIsLoading(
false
);
}
};
fetchData();
return
() => {
};
}, [url]);
return
{ data, isLoading, error };
}
function
AsyncComponent() {
const { data, isLoading, error } =
useEffect(() => {
if
(data) {
console.log(
'Data fetched:'
, data);
}
}, [data]);
useEffect(() => {
if
(error) {
console.error(
'Error fetching data:'
, error);
}
}, [error]);
return
(
<div>
{isLoading && <p>Loading...</p>}
{data && (
<ul>
{data.map(item => (
<li key={item.id}>{item.title}
<b>Price</b> {item.price}
</li>
))}
</ul>
)}
</div>
);
}
export
default
AsyncComponent;