Debug School

rakesh kumar
rakesh kumar

Posted on

How to display filtered data dynamically using react custom hooks use state and use effect

display filtered data dynamically
display filtered data while event trigger dynamically

display filtered data dynamically

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('https://api.example.com/data');
        const data = await response.json();

        // Apply condition to filter the data
        const filteredData = data.filter((item) => item.condition === 'some value');

        // Set the filtered data in the state
        setData(filteredData);
        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>
        {data.map((item) => (
          <li key={item.id}>{item.name}</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. Inside the useEffect hook, an async function fetchData is defined to fetch data from an API endpoint or database. The fetched data is then filtered based on a condition using the filter array method. The filtered data is then stored in the data state variable.

After the data is fetched and filtered, the component renders the data. While the data is being fetched, a loading message is displayed. If an error occurs during fetching, an error message is displayed.

Finally, the component renders the filtered data dynamically by mapping over the data state and displaying the relevant information, such as the name of each item, in a list.

Note: Make sure to replace 'API_ENDPOINT' with the actual API endpoint or database URL from where you want to fetch the data.

display filtered data while event trigger dynamically

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

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

  const fetchData = async () => {
    try {
      // Perform an API call or database fetch to retrieve the data
      const response = await fetch('https://api.example.com/data');
      const data = await response.json();

      // Apply condition to filter the data
      const filteredData = data.filter((item) => item.condition === condition);

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

  useEffect(() => {
    fetchData();
  }, [condition]);

  const handleButtonClick = () => {
    setIsLoading(true);
    fetchData();
  };

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

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

  return (
    <div>
      <h1>Data Display</h1>
      <button onClick={handleButtonClick}>Fetch Data</button>
      <input
        type="text"
        value={condition}
        onChange={(e) => setCondition(e.target.value)}
        placeholder="Enter condition"
      />
      <ul>
        {data.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default DataDisplay;
Enter fullscreen mode Exit fullscreen mode

display filtered data while select dropdown dynamically

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

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

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

      // Apply condition to filter the data based on the selected value
      const filteredData = data.filter((item) => item.condition === selectedValue);

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

  useEffect(() => {
    fetchData();
  }, [selectedValue]);

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

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

  const handleDropdownChange = (event) => {
    setSelectedValue(event.target.value);
  };

  return (
    <div>
      <h1>Data Display</h1>
      <select value={selectedValue} onChange={handleDropdownChange}>
        <option value="">Select Value</option>
        <option value="value1">Value 1</option>
        <option value="value2">Value 2</option>
        <option value="value3">Value 3</option>
      </select>
      <ul>
        {data.map((item) => (
          <li key={item.id}>{item.name}</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, error, and selectedValue. The fetchData function is defined outside the useEffect and is responsible for fetching the data based on the selectedValue.

Inside the useEffect hook, we specify that the effect should run whenever the selectedValue state changes. This means that when a value is selected from the dropdown, the effect is triggered, and the data is fetched based on the selected value.

The handleDropdownChange function is invoked when the dropdown value changes. It updates the selectedValue state with the new selected value.

The component renders the loading message, error message (if any), and the data dynamically. The dropdown allows the user to select a value, and when a value is selected, the data is filtered and displayed accordingly.

Top comments (0)