I am trying to use fetching helper function inside my functional component but for React complains:
src\components\Header.js
Line 19:30: React Hook "useFetch" is called in function "handleSearch" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter react-hooks/rules-of-hooks
I'm aware that functional components should start with a capital letter however, useFetch isn't a components, it's simply a helper function. What am I doing wrong? I know I can solve this by just calling my function UseEffect instead of useEffect but should I?
Here's my helper.js
import { useState, useEffect } from 'react';
export const GH_BASE_URL = 'https://api.github.com/';
export const useFetch = (url, options) => {
const [response, setResponse] = useState(null);
const [error, setError] = useState(null);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
const fetchData = async () => {
setIsLoading(true);
try {
const res = await fetch(url, options);
const json = await res.json();
setResponse(json);
setIsLoading(false);
} catch (error) {
setError(error);
}
};
if(url) {
fetchData();
}
}, []);
return { response, error, isLoading };
};
and my Header.js component
import React, { useState } from 'react';
import { useFetch, GH_BASE_URL } from '../helpers';
const REPO_SEARCH_URL = `${GH_BASE_URL}/search/repositories?q=`;
function Header(props) {
const [searchValue, setSearchValue] = useState('');
function handleChange(event) {
setSearchValue(event.target.value);
}
async function handleSearch(event) {
event.preventDefault();
const response = useFetch(`${REPO_SEARCH_URL}${searchValue}`);
}
return (
<header>
<form
onSubmit={handleSearch}
className="container"
>
<input
value={searchValue}
onChange={handleChange}
className="search-input"
placeholder="Search a repository">
</input>
</form>
</header>
);
}
export default Header;
useFetchis a perfectly natural pattern and would be called a custom hook. That documentation also describes why @Zachary's answer is correct.