0

odd question. if I wanted to make sure that my query ran for at least X seconds (e.g. 1sec), how would you tackle that? I have React Query that looks like this, but really just need the axios call to have some kind of time tracker on it.

import axios from 'axios';
import { useQuery } from 'react-query';
import { themeKeys } from './themeKeys';
import { webApiBaseUrl, config } from "../apiConstants";

export const fetchTheme = (themeId) =>
    axios.get(`${webApiBaseUrl}/themes/${themeId}`, config)
        .then((res) => res.data);

export default function useTheme(themeId) {
    return useQuery(
        themeKeys.theme(themeId), 
        () => fetchTheme(themeId),
        {
            failureCount: 3,
            retryOnMount: false,
            refetchOnMount: false,
            refetchOnWindowFocus: false,
            refetchOnReconnect: false,
            cacheTime: Infinity,
            staleTime: Infinity
        }
    );
}

I have something like this adding a delay, but not sure how to track how long the axios call ran for to deduct from the wait

export const fetchTheme = async (themeId) => {
    return axios.get(`${webApiBaseUrl}/themes/${themeId}`, config)
        .then((res) => res.data)
        .then( await wait(750));
};

function wait(ms) {
    return new Promise( (resolve) => {
        setTimeout(resolve, ms);
    });
}
Paul DeVito
  • 1,542
  • 3
  • 15
  • 38

1 Answers1

1

Put both of your promises inside Promise.all. That way if fetch finished first Promise.all will wait for wait to finish.

await Promise.all([fetchTheme(themeId), wait(750)])
aleksxor
  • 7,535
  • 1
  • 22
  • 27