Debug School

rakesh kumar
rakesh kumar

Posted on

How to display key value pair data dynamically using react custom hooks

import React, { useState, useEffect } from 'react';

const DataDisplay = () => {
  const [data, setData] = useState({});
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        // Perform an API call or database fetch to retrieve the data
        const response = await fetch('API_ENDPOINT');
        const jsonData = await response.json();

        // Set the data in the state
        setData(jsonData);
        setIsLoading(false);
      } catch (error) {
        setError(error);
        setIsLoading(false);
      }
    };

    fetchData();
  }, []);

  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  return (
    <div>
      <h1>Data Display</h1>
      <ul>
        {Object.entries(data).map(([key, value]) => (
          <li key={key}>
            <strong>{key}:</strong> {value}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default DataDisplay;
Enter fullscreen mode Exit fullscreen mode

In the above example, the DataDisplay component uses the useState hook to manage the state of data, isLoading, and error. The fetchData function is defined inside the useEffect hook and is responsible for fetching the data from the specified API endpoint.

Inside the useEffect hook, we call the fetchData function when the component mounts, indicated by the empty dependency array ([]). This ensures that the data is fetched only once when the component is first rendered.

The fetched data is stored in the data state using setData and is accessed as a key-value pair object. We use Object.entries(data) to convert the object into an array of key-value pairs. Then, we use .map() to iterate over the array and render each key-value pair as a list item.

Top comments (0)