swrv
swrv copied to clipboard
handle errors gracefully when dependently fetching
If I use an async fetcher, I get the following error in my console. It does actually work once the first call resolves. Is there more I should be doing, or some way to get rid of the errors?
vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in getter for watcher "function () {
return "/api/users/".concat(user.value.id, "/profile");
}": "TypeError: Cannot read property 'id' of undefined"
I've setup a simple test project with effectively the same code as shown here https://guuu.io/2020/data-fetching-vue-composition-api/#swrv
<template>
<div class="home">
<div>{{ profile.firstName }} {{ profile.lastName }}</div>
<div>{{ user.username }}</div>
</div>
</template>
<script>
import useSWRV from 'swrv';
const fetcher = async (key) => {
if (key === '/api/users/john') {
return { id: 1, username: 'john' };
} else if (key === '/api/users/1/profile') {
return { firstName: 'John', lastName: 'Doe' };
}
};
export default {
name: 'UserProfile',
props: {
username: {
type: String,
required: true,
},
},
setup(props) {
const { data: user } = useSWRV(`/api/users/${props.username}`, fetcher);
const { data: profile } = useSWRV(() => `/api/users/${user.value.id}/profile`, fetcher);
return {
user,
profile,
};
},
};
</script>
Here is the route for completeness sake
{
path: '/profile/:username',
component: () => import('../views/Profile.vue'),
props: (route) => ({ username: route.params.username }),
},
@bnason this is a known issue, unfortunately. Due to https://github.com/vuejs/composition-api/issues/242, I am unable to guard against reference errors thrown in the watchers for the time being. However, you can guard against it by doing a reference check:
https://github.com/Kong/swrv/blob/a9dbe75a437e9772448277cbe94de1117d1e806f/tests/use-swrv.spec.tsx#L155-L157
if the key resolves to false
, then it will not fire the fetcher and you will not see errors. Hope this helps.
keeping this open until composition function or vue 3 or something we can do make this more ergonomic / fixes it