Created
March 31, 2026 12:21
-
-
Save lejonmanen/eb159deca4a80b82eba06adbacc9844f to your computer and use it in GitHub Desktop.
React Suspense exempel
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
| // App.jsx | |
| import { Suspense } from 'react' | |
| import './App.css' | |
| import Loading from './Loading' | |
| import Consumer from './Consumer' | |
| const App = () => ( | |
| <div> | |
| <Suspense fallback={<Loading />}> | |
| <Consumer /> | |
| </Suspense> | |
| </div> | |
| ) | |
| export default App | |
| // Loading.jsx | |
| const Loading = () => ( | |
| <div> | |
| Loading... | |
| </div> | |
| ) | |
| export default Loading | |
| // Consumer.jsx | |
| import { use, useState } from "react" | |
| const initialPromise = myFetch() | |
| // Hämta skämt från Chuck Norris API | |
| async function myFetch() { | |
| const response = await fetch('https://api.chucknorris.io/jokes/random') | |
| const data = await response.json() | |
| return data.value | |
| } | |
| const Consumer = () => { | |
| const [promise, setPromise] = useState(initialPromise) | |
| const joke = use(promise) | |
| return ( | |
| <div> | |
| <h1> Chuck Norris API </h1> | |
| <p> {joke} </p> | |
| <button onClick={() => setPromise(myFetch())}> Another one! </button> | |
| </div> | |
| ) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment