skip to Main Content

lets assume we have a API with a query params which keeps changing as a timestamp

https://example.com/api/example?timestamp=1684522021000

once using RTK hook

const timestamp = dayjs().unix() * 1000;

const query = useFetchDataQuery(
    `example.com/api/example?${timestamp}`,
  );

if API get failed its keeps calling api until app crash
enter image description here

I tried using retry soultion , skip soulution but every time RTK consider it as a new API

thanks in advanced

2

Answers


  1. you can use skip to jump those cases

    const { data } = useFetchDataQuery(
        { tenantKey, page: 0, size: 100 },
        { skip: !your variables },
      )
    
    Login or Signup to reply.
  2. const cache = {};
    
    async function useFetchDataQuery( url ){
        // Get full baseurl from input url
        const a = document.createElement('a');
        a.setAttribute( 'href', url );
        const query = new URL( a.href );
        const baseurl = query.origin + query.pathname;
    
        // Set baseurl counter
        if( !cache[baseurl] ) cache[baseurl] = 0;
    
        // Exit if baseurl is requested more than 5 times
        if( cache[baseurl] >= 5 ) return;
    
        // Increment baseurl request
        cache[baseurl]++;
        
        // Fetch url
        return await fetch( url ).then( res => {
                // delete request from cache
                delete cache[baseurl];
    
                // return result
                return res.json();
            })
            .catch( error => {
                // log error
                console.error( error );
    
                // try again in 5 sec
                setTimeout( () => useFetchDataQuery( url ), 5000 );
    
                return null;
            });
    
    }
    
    useFetchDataQuery( `/api/example?timestamp=${timestamp}` );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search