Blog>
Snippets

Implementing a Placeholder Component while Data Loads

Illustrate creating and using a placeholder component in React to display a loading state while data is being fetched asynchronously for the infinite scroll feature.
function PlaceholderComponent() {
  return (
    <div>Loading...</div>
  );
}
Defines a simple PlaceholderComponent that shows a 'Loading...' message. This component is displayed while the data is being fetched.
function InfiniteScrollComponent() {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    // Simulate fetching data
    const fetchData = async () => {
      setLoading(true);
      // Simulated fetch call
      const newItems = await new Promise(resolve => setTimeout(() => resolve(['item 1', 'item 2']), 1000));
      setItems(prevItems => [...prevItems, ...newItems]);
      setLoading(false);
    };

    fetchData();
  }, []);

  return (
    <>
      {items.map(item => (
        <div key={item}>{item}</div>
      ))}
      {loading && <PlaceholderComponent />}
    </>
  );
}
Implements an InfiniteScrollComponent that fetches data and updates its state. While data is fetching, it displays the PlaceholderComponent.