I made a custom hook that fetches a News API and returns a handler for loading, errors and data (inspired by Apollo Client). The problem is that when using it, it will fire itself infinitely, even though the items in the dependency array don't change. This is how I'm implementing it:
The hook:
const useSearch = (query: string, sources: string[]) => {
const [response, setResponse] = useState<State>({
data: null,
loading: true,
error: null,
});
useEffect(() => {
newsapi
.getEverything({
q: query,
pageSize: 1,
sources: sources,
})
.then((data) => {
setResponse({ data, loading: false, error: null });
})
.catch((e) => {
setResponse({ data: null, loading: false, error: e });
});
}, [query, sources]);
return response;
};
Usage:
const { loading, error, data } = useSearch("Donald", ["bbc-news"]);
And I exceeded my daily rate for the API:
What am I doing wrong?