Search code examples
reactjsjsonintervals

fetching a json every second


Hello I need to implement a realtime app with reactjs. Now I need to make the function that fetches the realtime json every second. what is the best way to do that?


Solution

  • To fetch data from an API in React and update it in real-time, you can use a combination of useEffect and setInterval.

    function ScoresApp() {
    const [matchData, setMatchData] = useState(null);
    const [realtimeData, setRealtimeData] = useState(null);
    useEffect(() => {
    // Fetch match data (general information) once
    fetchMatchData();
    
    // Fetch real-time data every second
    const interval = setInterval(fetchRealtimeData, 1000);
    
    // Clean up the interval on component unmount
    return () => clearInterval(interval); }, []);
    
    const fetchMatchData = async () => {
    try {
      const response = await fetch('your-match-data-api-url');
      const data = await response.json();
      setMatchData(data);
    } catch (error) {
      console.error('Error fetching match data:', error)};
    const fetchRealtimeData = async () => {
    try {
      const response = await fetch('your-realtime-data-api-url');
      const data = await response.json();
      setRealtimeData(data);
    } catch (error) {
      console.error('Error fetching real-time data:', error);
    }};
    return (
    <div>
      {/* Render the match data */}
      {matchData && (
        <div> <h2>Match Information</h2> </div>)}
      {realtimeData && (
        <div> <h2>Real-Time Scores</h2> </div>)}</div>)}