call useFetch when selecting options
Hello everybody,
I want to create an app just like this: https://rssw.com/search-by-vehicle. Every next select element must call its useFetch hook when the last one has already been called.
useFetch.js:
export function useFetch(url) {
const [response, setResponse] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch(url)
.then((res) => res.json())
.then((jsonData) => {
setResponse(jsonData);
setIsLoading(false);
})
.catch((error) => {
setError(error);
setIsLoading(false);
});
}, []);
return [response, isLoading, error];
}
Right now two useFetch hooks have been called instantly and the URLs are hard-coded. For example, I want to pass the selected year option to getMake
URL.
const api_key = process.env.REACT_APP_API_KEY;
function App() {
const getYear = "getYear";
const getMake = "getMake";
const urlGetYear = `https://api.macpek.com/apiv3/${getYear}/?key=${api_key}`;
const urlGetMake = `https://api.macpek.com/apiv3/${getMake}/?key=${api_key}&year=2019`;
const [yearData, isLoadingYear, errorYear] = useFetch(urlGetYear);
const [makeData, isLoadingMake, errorMake] = useFetch(urlGetMake);
if (errorYear || errorMake) {
return <p>Sorry, something went wrong.</p>;
}
return (
<div className="App">
<header className="App-header">
<h2>Search by vehicle</h2>{" "}
{isLoadingYear ? (
"Loading..."
) : (
<select>
{yearData.Macpek.years.map((year, index) => (
<option key={index}>{year}</option>
))}
</select>
)}
{isLoadingMake ? (
"Loading..."
) : (
<select>
{makeData.Macpek.makes.map((year, index) => (
<option key={index}>{year}</option>
))}
</select>
)}
</header>
</div>
);
}
How can I do that?