Concurrent Mode - App.js
This file contains 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 React, { useState, useEffect, unstable_useTransition, Suspense } from 'react'; | |
import Spinner from 'react-bootstrap/Spinner' | |
import 'bootstrap/dist/css/bootstrap.min.css'; | |
import './App.css'; | |
const ImageList = React.lazy(() => import('./Components/ImageList')); | |
const App = () => { | |
const [images, setImages] = useState(); | |
const [startTransition, isPending] = unstable_useTransition(1000); | |
const fetchImages = () => { | |
return fetch('https://jsonplaceholder.typicode.com/photos').then((res) => res.json()); | |
} | |
const createResource = () => { | |
let status = 'loading'; | |
let result; | |
const suspender = fetchImages().then( | |
(data) => { | |
status = 'success'; | |
result = data; | |
}, | |
(error) => { | |
status = 'error'; | |
result = error; | |
}, | |
); | |
return { | |
read() { | |
if (status === "loading") { | |
throw suspender | |
} else if (status === "error") { | |
throw result | |
} else if (status === "success") { | |
return result | |
} | |
}, | |
}; | |
} | |
useEffect(() => { | |
startTransition(() => { | |
setImages(createResource()); | |
}); | |
}, []); | |
const loadingPhotos = () => { | |
return ( | |
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginTop: '3em' }}> | |
<Spinner animation="border" /> | |
<b>Loading photos</b> | |
</div> | |
) | |
} | |
return ( | |
<div className="container" > | |
<h1>Gallery</h1> | |
<div style={{ display: 'flex', flexDirection: 'row', justifyContent: "center", width: '100%' }}> | |
<Suspense fallback={loadingPhotos()}> | |
<ImageList resource={images} pending={isPending} /> | |
</Suspense> | |
</div> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment