0

I try to pass isLoading state to button prop when click button which trigger refetch function from useQuery, and it doesn't work (maybe because it re-render component and when component render isLoading is false). I wonder how i can make it works?

const MainPage: React.FC = () => {

    const {data, isLoading,  error, refetch} = useQuery<any>(
        ["getCity"],
        () => fetchCities(),
        {
                enabled: false,
            }
        )

    return (
        <div>
            <div>
                {JSON.stringify(data)}
            </div>
            <Button
                    loading={isLoading} //  always false. Need to be true when start refetch and false by the end refetch
                    label="get_cities"
                    onClick={() => refetch()}
            >

            </Button>
        </div>

    )
}

export default MainPage;

1
  • Is it false, when you try load the data for the first time as well? Commented Jul 3, 2022 at 16:18

1 Answer 1

4

isLoading will become true only when query has no data and is currently fetching while isFetching will become true if the query is fetching at any time (including background refetching).

In your case, just use isFetching instead of isLoading

const { isLoading, isFetching } = useQuery(...);

if(isLoading){
    return <div>Loading cities...</div>
}

return <Button
    loading={isFetching}
    label="get_cities"
    onClick={() => refetch()}
>
Sign up to request clarification or add additional context in comments.

Comments

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.