Skip to content

Instantly share code, notes, and snippets.

@mikamboo
Last active July 15, 2020 11:39
Show Gist options
  • Select an option

  • Save mikamboo/62aed6565fa68985dd293f83f517788b to your computer and use it in GitHub Desktop.

Select an option

Save mikamboo/62aed6565fa68985dd293f83f517788b to your computer and use it in GitHub Desktop.
import React, { useState, useEffect } from "react";
const FetchData = () => {
const [status, setStatus] = useState("idle");
const [query, setQuery] = useState("");
const [data, setData] = useState([]);
useEffect(() => {
if (!query) return;
(async () => {
setStatus("fetching");
const response = await fetch(
`https://hn.algolia.com/api/v1/search?query=${query}`
);
const data = await response.json();
setData(data.hits);
setStatus("fetched");
})();
}, [query]);
return (
<>
<h1>fetch Data</h1>
<input
type="text"
value={query}
onChange={e => setQuery(e.target.value)}
/>
<p>Status : {status}</p>
<pre>{JSON.stringify(data, undefined, 2)}</pre>
</>
);
};
export default FetchData;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment