Defer running of mutation so it's not running on component setup
See original GitHub issueI’m using useAsyncGql
to run a mutation. I’m defining it in the component setup, but I want to defer running the mutation until a button is clicked. When the button is clicked, I run the refresh() function.
However, the mutation is also running on component setup. I wish to prevent that because it’s polluting the error ref and making an unneccesary request.
I tried using lazy: true in the configuration:
<script setup>
const { data, error, refresh, pending } = await useAsyncGql("createTodo", {
todo: addTodo
}, {
lazy: true
});
const submit = async () => {
await refresh();
}
</script>
This code will attempt to run the mutation on component load.
How can I prevent it from running on component setup? 😃
Issue Analytics
- State:
- Created a year ago
- Comments:5 (3 by maintainers)
Top Results From Across the Web
Mutations in Apollo Client - Apollo GraphQL Docs
Unlike useQuery , useMutation doesn't execute its operation automatically on render. Instead, you call this mutate function.
Read more >Why can't I directly modify a component's state, really?
This answer is to provide enough information to not change/mutate the state directly in React. React follows Unidirectional Data Flow.
Read more >Scripts: async, defer - The Modern JavaScript Tutorial
The defer attribute tells the browser not to wait for the script. Instead, the browser will continue to process the HTML, build DOM....
Read more >Redux Essentials, Part 8: RTK Query Advanced Patterns
The official Redux Essentials tutorial: learn advanced patterns for fetching data with RTK Query.
Read more >React useLayoutEffect vs. useEffect with examples
React hands over the details about the DOM mutation to the browser engine ... “the function passed to useEffect will run after the...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
This solution works, but I think it would be cleaner if there was a native alternative. How about something like:
This way we wouldn’t need to define custom refs to keep track of data and assign it.
Thanks for getting back to me. Oh nice, I didn’t realize that functions are generated like that! Cool stuff.
I’ll give it a try and then post my solution here. Hopefully I can contribute with adding this to the docs afterwards.