N
Nuxtβ€’15mo ago
Quentin

useFetch update my data without assignment

Hi guys, I must have missed something, but I found something weird using useFetch. It looks like there's a kind of link between requests on the same URL. Here's my code for an example:
<script setup>
/**
* API fetch
*
* @param {String} url
* @param {Object} options
* @returns {Object}
*/
const fetch = (url, options) => {
return useFetch(url, {
baseURL: apiUrl(),
headers: {
accept: 'application/json',
'X-XSRF-TOKEN': useCookie('XSRF-TOKEN').value,
},
credentials: 'include',
...options,
})
}

// Get a json object { test: 'get' }
const { data: test } = await fetch('v1/test');

const post = () => {
// Get a json object { test: 'post' }
fetch('v1/test', { method: 'POST' });
};
</script>

<template>
Test: {{ test }}
<input type="button" value="Click me" @click="post"/>
</template>
<script setup>
/**
* API fetch
*
* @param {String} url
* @param {Object} options
* @returns {Object}
*/
const fetch = (url, options) => {
return useFetch(url, {
baseURL: apiUrl(),
headers: {
accept: 'application/json',
'X-XSRF-TOKEN': useCookie('XSRF-TOKEN').value,
},
credentials: 'include',
...options,
})
}

// Get a json object { test: 'get' }
const { data: test } = await fetch('v1/test');

const post = () => {
// Get a json object { test: 'post' }
fetch('v1/test', { method: 'POST' });
};
</script>

<template>
Test: {{ test }}
<input type="button" value="Click me" @click="post"/>
</template>
On the first load, my page shows Test: { "test": "get" }, that is what I wanted to do, fine. But when I click on the button, the page shows Test: { "test": "post" } and I don't understand why. I expected to see Test: { "test": "get" } again, as I didn't change the test variable by myself. Any idea? Thanks
2 Replies
πŸ‡¨πŸ‡­ Marko Bolliger <cannap>
maybe you want $fetch i use "useFetch" only for the first call https://discord.com/channels/473401852243869706/1075465297974263868
Quentin
Quentinβ€’15mo ago
Ok I wanted to factorize all my API calls into a custom plugin to add them some options. But I assume that I just have to make a .get() function using useFetch, and post, put etc using $fetch ?
Want results from more Discord servers?
Add your server