skip to Main Content

I am displaying data from another application so when the new data added to that app i want my application get that data and update the UI with the latest data. I am using webhook to get the newly added data and then storing that on my application DB. But can’t show the updated data until reload.

2

Answers


  1. For these kind of immediate changes, we usually do data pooling or in this case, web sockets. Consider using socket.io as an example but if you are in a serverless environment, like NextJS’s API routes, it’s not possible to use web sockets. You can use SaaS as Pusher to achieve what you are looking for.

    Or, if you don’t mind, you can keep calling API after 1 minute:

    import { useEffect } from 'react';
    import axios from 'axios';
    
    const ApiCaller = () => {
      useEffect(() => {
        // Function to call the API
        const callApi = async () => {
          try {
            const response = await axios.get('https://api.example.com/endpoint');
            console.log('API Response:', response.data);
          } catch (error) {
            console.error('Error calling API:', error);
          }
        };
    
        // Call the API immediately and then set an interval
        callApi();
        const intervalId = setInterval(callApi, 60000); // 1 minute interval
    
        // Cleanup on component unmount
        return () => clearInterval(intervalId);
      }, []); // Empty dependency array ensures it runs once
    
      return <div>API Caller Component</div>;
    };
    
    export default ApiCaller;
    

    Or more better query using TanStack Query:

    import { useQuery } from '@tanstack/react-query';
    import axios from 'axios';
    
    const fetchData = async () => {
      const response = await axios.get('https://api.example.com/endpoint');
      return response.data;
    };
    
    const ApiCaller = () => {
      const { data, error, isLoading } = useQuery(
        ['apiData'],
        fetchData,
        {
          refetchInterval: 60000, // Automatically refetch every 1 minute
          refetchOnWindowFocus: false, // Disable refetch on focus
        }
      );
    
      if (isLoading) return <div>Loading...</div>;
      if (error) return <div>Error fetching data: {error.message}</div>;
    
      return (
        <div>
          <h1>API Data</h1>
          <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
      );
    };
    
    export default ApiCaller;
    
    

    These are just examples, configure as you are expecting.

    Login or Signup to reply.
  2. You can run a polling logic inside a useEffect hook and update a state variable to save the state. Refer the example mentioned in the below post.

    React hooks. Periodic run useEffect

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search