Use Refetch from Vue 3 useQuery Composable to Ensure Fresh Data

Share this video with your friends

Social Share Links

Send Tweet

Since we are preventing a page refresh on form submit, we don't see that our data is updated in the UI until we manually refresh the page.

We can display the correct data without a refresh by using the refetch method from the composable useQuery. In this lesson, we will emit an updated event that triggers a handleRefresh method, inside of which is a call to refetch.

Instructor: [0:00] At the moment, when we update our craft, change its EHD-18, the state of the web page doesn't update with the data change. We have to refresh the page in order to get the cache to update. Let's fix that. What I want is for my updateCraft form to emit an event that tells my craft view that it should refresh the data.

[0:20] To do that, in my defined emits, I'm going to add a new emit called updated. Then, in my handleSubmit, that's the event I want to emit. Back at my craft view, I want to listen now for that event, so updated. What do I want to do when I receive the updated event? I want to handleRefresh.

[0:40] In my script, I'm going to create that function, so function handleRefresh. The first thing I want to do is to close the modal, so modal.value is going to equal false. The second thing, I just want to refresh the data. To do that, I'm going to go back to my useQuery function here. I destructured the result. I can also destruct the function Refetch, which I can call inside my handleRefresh.

[1:06] Let's try that now. I'll update to be 181 months, update, and it's updated and refetched. I'm going to close this. Let's try to change the name to 1556. Again, by the time the window has closed, it's already updated.