Search code examples
reactjsreact-hooksuse-effectreact-query

React-Query: Trigger a re-render in component when a query is re-fetched due to a mutation calling invalidateQueries in a sub-component


I'm using react-query in a Posts component that renders a PostForm component followed by a list of PostView components.

--Posts--

const [ isLoading, data ] = useQuery("get_posts", {...}, )

const [ userPosts, setUserPosts] = useState([]);
const [ isReady, setIsReady ] = useState(false);

useeffect(() => {
    newPosts = ..do some things with the data
    setUserPosts(newPosts)
    setIsReady(true);
}, [isLoading])

return !isReady ? null : (
    <PostForm />
    posts.current.map(post => <PostView key={post.id} Content={post} />
)

--PostForm--

const mutation = useMutation(
    () => { ... },
    { onSuccess: queryClient.invalidateQueries("get_posts")}
)

const submitHandler = e => {
    const newPost = ...
    mutation.mutate(newPost)
}

return ( a form wired to the submitHandler )

When the mutation is called in PostForm and the query in Posts gets invalidated I can see the new GET request being made with the new post added in, but I also would expect isLoading being set to true and then false and that to trigger the dependency array of the useEffect hook in Posts.

Isn't the isLoading value being reset while the query is refetched? How can I trigger a re-render on my Posts component when the mutation invalidates the previous query results?


Solution

  • isLoading is only set to true if there is no data before while fetching, like when you load your app at the first time. If there is already data (including cache data), and you're doing subsequent refetches, you can use isFetching to indicate the fetching state.