Skip to content

Instantly share code, notes, and snippets.

@treshugart
Last active May 6, 2024 05:02
Show Gist options
  • Save treshugart/6eff0da3c0bea886bb56589f743b78a6 to your computer and use it in GitHub Desktop.
Save treshugart/6eff0da3c0bea886bb56589f743b78a6 to your computer and use it in GitHub Desktop.
Skate mixin to rehydrate props and state on the client.

withRehydration

This is a Skate mixin for serialising and rehydrating props and state for a component. Essentially it will apply JSON encoded attributes for props and state after rendering on the server. When rendered on the client, it then takes those attributes and decodes them as props, essentially rehydrating the component state.

Notes

  • The didMount callback is specific to Skate and is called after the component is connected.
  • The didRender callback is specific to Skate and is called after the component renders.
const hasProcess = typeof process !== 'undefined';
const isBrowser = !hasProcess || hasProcess && process.browser;
function esc(str) {
return escape(str ? JSON.stringify(str) : '');
}
function usc(str) {
return str ? JSON.parse(unescape(str)) : '';
}
export const withRehydration = (Base = HTMLElement) =>
class extends Base {
didMount() {
if (super.didMount) {
super.didMount();
}
if (isBrowser) {
this.props = usc(this.getAttribute('props'));
this.state = usc(this.getAttribute('state'));
this.removeAttribute('props');
this.removeAttribute('state');
}
}
didRender() {
if (super.didRender) {
super.didRender();
}
if (!isBrowser) {
this.setAttribute('props', esc(this.props));
this.setAttribute('state', esc(this.state));
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment