Blog>
Snippets

Integrating External APIs with TanStack Ranger Components

Illustrate the process of fetching data from an external API and integrating it with a Ranger component for a dynamic data table.
import { useState, useEffect } from 'react';
import { useRanger } from 'react-ranger';
Import necessary hooks from React and the useRanger hook from react-ranger.
function fetchData(setData) {
  // Replace 'your-api-endpoint' with the actual API endpoint
  fetch('your-api-endpoint')
    .then(response => response.json())
    .then(data => setData(data))
    .catch(error => console.error('Error fetching data:', error));
}
Define a function to fetch data from an external API and update the state with the fetched data.
function DynamicRanger() {
  const [data, setData] = useState([]);
  const [values, setValues] = useState([0, 100]);

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

  const { getTrackProps, handles } = useRanger({
    min: 0,
    max: 100,
    stepSize: 1,
    values,
    onChange: setValues
  });

  return (
    <div {...getTrackProps()}>
      {handles.map(({ getHandleProps }) => (
        <button {...getHandleProps()} />
      ))}
    </div>
  );
}
Create a React component that fetches data on mount and uses the useRanger hook to create a ranger component. The data fetched doesn't directly interact with the ranger but is intended to show how to fetch and utilize asynchronous data in tandem with TanStack Ranger. Adjust the 'min', 'max', and 'stepSize' as needed based on your data.