Skip to content

Instantly share code, notes, and snippets.

@ahmetcanisik
Last active April 28, 2025 18:57
Show Gist options
  • Save ahmetcanisik/c22f11e8ab4ac2adffe42b9c33ad54a2 to your computer and use it in GitHub Desktop.
Save ahmetcanisik/c22f11e8ab4ac2adffe42b9c33ad54a2 to your computer and use it in GitHub Desktop.
[Fetch and Write data- React] Fetch datas and write to components in React
import { useEffect, useState } from "react";
interface ResponseData {
userId: number;
id: number;
title: string;
body: string;
}
function App() {
const [content, setContent] = useState<null | ResponseData>(null);
const [error, setError] = useState<null | string>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(res => {
if (res.ok) {
setError(null);
setLoading(false);
return res.json();
}
throw new Error("Response is not ok!");
})
.then(data => {
setContent(data);
setLoading(false);
setError(null);
})
.catch(err => {
setError(err)
setLoading(false);
})
}, []);
if (loading) {
return <div>loading...</div>;
}
if (error) {
return <div>{error}</div>
}
return <div>{content && content?.title}</div>;
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment