Skip to content

Instantly share code, notes, and snippets.

@joaquin-viera
Last active September 24, 2020 06:57
Show Gist options
  • Save joaquin-viera/137d1f066c0c481ed3c016aa8e55da9e to your computer and use it in GitHub Desktop.
Save joaquin-viera/137d1f066c0c481ed3c016aa8e55da9e to your computer and use it in GitHub Desktop.
Concurrent Mode - App.js
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