Skip to content

Instantly share code, notes, and snippets.

@ixtk
Created January 24, 2024 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ixtk/2470f8ce7edb71b86b00eb7515153a15 to your computer and use it in GitHub Desktop.
Save ixtk/2470f8ce7edb71b86b00eb7515153a15 to your computer and use it in GitHub Desktop.
import "./App.css"
import { useState } from "react"
function App() {
const [loading, setLoading] = useState(false)
const demoFetch1 = () => {
fetch("https://jsonplaceholder.typicode.com/comments")
.then((response) => {
// 200-299
if (response.ok === false) {
throw new Error("Something went wrong")
}
return response.json()
})
.then((data) => console.log('Final data:', data))
.catch((error) => console.warn('Problem:', error.message))
}
const demoFetch2 = async () => {
try {
setLoading(true)
const response = await fetch("https://jsonplaceholder.typicode.com/asdlfkj")
console.log(response)
if (response.ok === false) {
throw new Error("Something went wrong")
}
const data = await response.json()
console.log(data)
} catch(error) {
console.warn('Problem:', error.message)
}
setLoading(false)
}
return (
<>
<div>
<h1>Fetch</h1>
{loading && "Loading..."}
<button onClick={demoFetch2}>Try it</button>
</div>
</>
)
}
export default App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment