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);
    });
}
1

1 Answer 1

2

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)])
Sign up to request clarification or add additional context in comments.

2 Comments

I like this, but need to return the response from fetchTheme for this to work. what does promise all return?
const [result, _] = await Promise.all([fetch(), wait()]) it returns an array of resolved results

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.