Last active
April 28, 2025 18:57
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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