Skip to content

Instantly share code, notes, and snippets.

@Jamiewarb
Last active January 6, 2022 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jamiewarb/c47a893cf929570aa38e5caeb3616dc8 to your computer and use it in GitHub Desktop.
Save Jamiewarb/c47a893cf929570aa38e5caeb3616dc8 to your computer and use it in GitHub Desktop.
Example of useFetch serialisation stripping away functions from object during clientside hydration
<template>
<h1>{{ someObj.someFunction() }}</h1>
</template>
<script>
import { useFetch } from '@nuxtjs/composition-api';
import { doSomethingAsync } from './helpers';
export default {
setup() {
function someFunction() { return 'test' };
const someObj = { someFunction };
useFetch(async () => {
await doSomethingAsync();
});
return { someObj };
}
};
</script>
/**
* During serverside rendering, someObj.someFunction can be called correctly in the template.
* During clientside hydration, someObj becomes an empty object `{}`, and the above template fails
* as "someObj.someFunction is not a function"
*
* If I remove the `useFetch()` call entirely, someObj no longer becomes an empty object during hydration.
* I believe `useFetch` must be serialising the objects for hydration, which is stripping all values
* that are functions, as they cannot be serialised.
*
* How can I avoid this behaviour?
* Using `onServerPrefetch` instead avoids this behaviour, but I imagine I'm losing the caching benefits of `useFetch`.
*/
@Jamiewarb
Copy link
Author

Jamiewarb commented Jan 6, 2022

Potentially I could use onServerPrefetch, and to wrap it up with clientside route changes too I could do something like this and use onSsr?

const hasRouteChanged = (vm) => {
  const { from } = vm.proxy.$router.app.context;
  const { current } = vm.proxy.$router.history;

  if (!from) {
    return false;
  }

  return from.fullPath !== current.fullPath;
};

function onSsr(fn {
  onServerPrefetch(fn);
  if (typeof window !== 'undefined') {
    const vm = getCurrentInstance();

    if (hasRouteChanged(vm)) {
      fn();
    }
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment