Skip to content

Instantly share code, notes, and snippets.

@cmaneu
Created February 13, 2025 13:59
Show Gist options
  • Save cmaneu/c31a03a94514fb0904123f38a17737ea to your computer and use it in GitHub Desktop.
Save cmaneu/c31a03a94514fb0904123f38a17737ea to your computer and use it in GitHub Desktop.
React - Long server answer example
import React, { useState, useEffect } from 'react';
// FakeFetch function to simulate a fetch request with a fixed delay of 10 seconds
const FakeFetch = url => {
return new Promise((resolve, reject) => {
const delay = Math.random() < 0.5 ? 0 : 10000; // Either 0ms or 10000ms (10 seconds)
console.log(`FakeFetch delay: ${delay}ms`);
setTimeout(() => {
// Simulate a successful response with dummy data
const dummyResponse = new Response(
JSON.stringify({ data: 'Dummy data from FakeFetch' }),
{
status: 200,
headers: {
'Content-Type': 'application/json',
},
}
);
resolve(dummyResponse);
}, delay);
});
};
const FetchWithLoadingMessages = () => {
const [data, setData] = useState(null);
const [loadingMessage, setLoadingMessage] = useState('Loading...');
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await FakeFetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const result = await response.json();
setData(result.data);
} catch (error) {
setError(error.message);
}
};
fetchData();
// Set a timeout to change the loading message after 2 seconds
const timeoutId = setTimeout(() => {
setLoadingMessage(
"We are using sustainable servers that pause off peak-hours. We'll need another minute or so..."
);
}, 2000);
// Cleanup the timeout if the component unmounts or data is fetched
return () => clearTimeout(timeoutId);
}, []);
if (error) {
return <div>Error: {error}</div>;
}
if (!data) {
return <div>{loadingMessage}</div>;
}
return <div>{data}</div>;
};
export function App(props) {
return (
<div className='App'>
<h1>Customers</h1>
<FetchWithLoadingMessages />
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment