Skip to content

Instantly share code, notes, and snippets.

@Tribhuwan-Joshi
Created January 18, 2023 05:22
Show Gist options
  • Select an option

  • Save Tribhuwan-Joshi/8c2e9ad6e0570d497afb5f5fb7c0b0fe to your computer and use it in GitHub Desktop.

Select an option

Save Tribhuwan-Joshi/8c2e9ad6e0570d497afb5f5fb7c0b0fe to your computer and use it in GitHub Desktop.
Custom hook
import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";
const useFetch = (url) => {
const [data, setData] = useState(null);
useEffect(() => {
fetch(url)
.then((res) => res.json())
.then((data) => setData(data));
}, [url]);
return [data]
};
const Home = () => {
const [data] = useFetch("https://jsonplaceholder.typicode.com/todos");
return (
<>
{data &&
data.map((item) => {
return <p key={item.id}>{item.title}</p>;
})}
</>
);
};
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Home />);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment