Get SSR attribute value when hydrating

Hi guys! The server generates an attribute value for an element and I don't want to re-generate that attribute value on the browser side because it's unnecessary load on the user device. Is it possible to access the to-be-updated element from within the client side component function code? e.g.
const myAttr = createSignal(isServer ? doHeavyCalculationThing() : hydrationEl.dataset.myAttr);

// return JSX using myAttr
const myAttr = createSignal(isServer ? doHeavyCalculationThing() : hydrationEl.dataset.myAttr);

// return JSX using myAttr
I do still need the doHeavyCalculationThing's code to be given to the client as it will need to re-calculate after an interaction. cheers!
6 Replies
thetarnav
thetarnav15mo ago
GitHub
solid-use/server-value.md at main · lxsmnsyc/solid-use
A collection of SolidJS utilities. Contribute to lxsmnsyc/solid-use development by creating an account on GitHub.
thetarnav
thetarnav15mo ago
I guess this is what it's for @lxsmnsyc
jimmyjamiejamesjimbob
hey @thetarnav thanks for sending this! helpful little library that - although this'll work, I'm wondering if I could somehow just read the element's attribute since that's already in the document anyway and looking at that library's source, it seems to create a script tag with the data duplicated to get it to the client - for this specific use case, accessing the element to-be-hydrated would be ideal!
thetarnav
thetarnav15mo ago
ah you certainly can I assume it has to happen in onMount for the ref to be populated otherwise you could use a query selector to get the el since it's already in the dom
jimmyjamiejamesjimbob
function retrieveSsrClass() {
const el = document.querySelector(`*[data-hk^="${sharedConfig.context?.id}"]`) as HTMLElement;
if (el == null) {
return null;
}

return el.getAttribute('class');
}
function retrieveSsrClass() {
const el = document.querySelector(`*[data-hk^="${sharedConfig.context?.id}"]`) as HTMLElement;
if (el == null) {
return null;
}

return el.getAttribute('class');
}
this is what I ended up doing, seems to work, don't know if it will work for every scenario aha and I'm sure there's a more efficient way of accessing the element, if anyone has any better ideas lmk! - thanks for your help @thetarnav!
lxsmnsyc
lxsmnsyc15mo ago
This goes beyond an element's attribute, like you can use this for components that do not render an element, directly or indirectly. It can also serialize beyond a string value This one potentially will cause hydration mismatches since I assume you'd want to run it before the element hydrates server-value beats that in every aspect