In my Nuxt app, I render a sorted list of events by start date, where some of these items start exactly at the same time. The comparison function is the following:
(a, b) => {
if (a.startTime < b.startTime) {
return -1
} else if (a.startTime > b.startTime) {
return 1
} else {
return 0
}
}
The problem is that in Firefox i get a The client-side rendered virtual DOM tree is not matching server-rendered content.
error. This error does not appear in Chromium.
I think that the problem comes from the return 0
statement in the above comparison function. MDN says:
If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
On a server-side render, Node JS engine sorts the events starting at the same time differently from Firefox JS engine when doing the hydration. Consequently, if the DOM changes between differently sorted events, a node mismatch error occurs (this does not happen if the DOM structure is the same but the text changes).
I've created a repo of an app that reproduces the problem: https://github.com/paumoreno/nuxt-node-mismatch. Rendering localhost:3000 in Firefox will cause a node mismatch error, whereas in Chrome it won't.
The error is easy to solve: in the array comparison function, instead of returning 0 for equal dates, simply sort the events by id (or any other deterministic comparison), and the problem is gone.
I think this should be explained in Nuxt documentation, as the cause of the node mismatch error is not obvious at all (I had to deconstruct all the app in order to find it).
What do you guys think? Has anyone else encountered this problem?
Thanks again for this great framework!
<!--cmty--><!--cmty_prevent_hook--><div align="right"><sub><em>This question is available on <a href="https://nuxtjs.cmty.io">Nuxt.js</a> community (<a href="https://nuxtjs.cmty.io/nuxt/nuxt.js/issues/c1917">#c1917</a>)</em></sub></div>