I can´t understand how the curly braces work (or what are they supposed to do) in the return of this custom hook. I know it´s destructuring, I just don´t understand the need for them. Could anyone explain?
const useHackerNewsApi = () => {
const [data, setData] = useState({ hits: [] });
const [url, setUrl] = useState(
'https://hn.algolia.com/api/v1/search?query=redux',
);
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
useEffect(() => {
const fetchData = async () => {
setIsError(false);
setIsLoading(true);
try {
const result = await axios(url);
setData(result.data);
} catch (error) {
setIsError(true);
}
setIsLoading(false);
};
fetchData();
}, [url]);
return [{ data, isLoading, isError }, setUrl];
}
You're basically returning an array that contains an Object at the 0th index and setUrl
method at the second index.
The return value would be implicitly converted into:
[{
data: data,
isLoading: isLoading,
isError: isError
}, setUrl]
That's why you'd be able to use it like this in your Component:
import React, { useState } from "react";
import { useHackerNewsApi } from "./useHackerNewsAPI";
export default ({ name }) => {
const [{ data, isLoading, isError }, setUrl] = useHackerNewsApi();
return <h1>
<pre> Data - { JSON.stringify(data) }</pre>
<pre> isLoading - { isLoading }</pre>
<pre> isError - { isError }</pre>
</h1>;
};
Here's a Working Demo for your ref.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.