question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Pass options to useFetch execute()

See original GitHub issue

Clear and concise description of the problem

Suppose I want to save a User.

<input v-model="user.id" />
<button @click="onSave(user)">
const user = ref({ firstname: '', lastName: '', id: '1' });

const useSaveUser = (user: Ref<User>) => {
  return useFetch(computed(() => `/api/user/${user.id}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(user.value) // this is not reactive :(
  }));
}

const { data, isFetching error, execute: onSave } = useSaveUser(user);

The URL is reactive, so when I call execute() it will call the endpoint /api/user/2 after I change the id into 2 with the input field. However the options are not reactive so I cannot PUT the updated user.

Am I missing something or is it pretty hard to use usefetch except for when you are fetching things?

Suggested solution

It would be nice if you can pass options to the execute method. These will be merged with the options that you already passed when calling useFetch.

const useSaveUser = (user: Ref<User>) => {
  return useFetch(computed(() => `/api/user/${user.id}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
  }));
}

const { data, isFetching error, execute } = useSaveUser(user);

const onSave = (user) => {
  execute(undefined, {
    url: `/api/user/${user.id}`,
    body: JSON.stringify(user)
  });
}

Alternative

As a workaround I can do something like this:

const isFetching = ref(false);
const showError = ref(false);
const onSave = (user) =>
  isFetching.value = true;
  showError.value = false;

  const { data, error } = await useFetch(`/api/user/${user.id}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(user)
  }));

  isFetching.value = false;
  showError = !!error.value;
}

However then I don’t make use of hooks and I need to keep redundant state. Then I can also use fetch or one of the available vanilla JS API clients.

Additional context

No response

Validations

Issue Analytics

  • State:open
  • Created a year ago
  • Comments:12

github_iconTop GitHub Comments

1reaction
fvanwijkcommented, Oct 24, 2022

In the mean time I created this full example, including error handling.

So the main differences with your example are:

  1. Supports PUT and POST depending on which button you click
  2. The userRef should not be updated when we click Save as. It should create a copy that is POSTed. Hence the need for passing a different payload to execute 😃

https://stackblitz.com/edit/vue-hbnfxy?file=src/App.vue

This the same example but then fully working as expected, because everything is reactive. The code however is horrible.

https://stackblitz.com/edit/vue-hcwdn3?file=src%2FApp.vue

0reactions
fvanwijkcommented, Nov 2, 2022

I mean options like headers and method

Read more comments on GitHub >

github_iconTop Results From Across the Web

useFetch
This fetch is run onMount/componentDidMount . The last argument [] means it will run onMount . If you pass it a variable like...
Read more >
Allow passing arguments to run with useFetch #75 - GitHub
Hi there, I have the following use case: I want to use useAsyncFetch in a function component with formik. That looks something like...
Read more >
useFetch - VueUse
Reactive Fetch API provides the ability to abort requests, intercept requests before they are fired, automatically refetch requests when the url changes, and ......
Read more >
await useFetch and then passing data to another react hook
The problem is that data is undefined until it finishes fetching, and usePagination crashes. and being that it is a hook you can't...
Read more >
Custom Hooks in React: useFetch - Alyssa Holland's Blog
There is a fetch() method that allows you to send a network request and ... Additionally, you can pass in a second argument,...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found