Hi there!
Hope you are doing well! So this blog post is about the Curious Case of "missing" object properties that were added during coding but went missing during the runtime.
Ok. Might be a shocker! How can some properties get deleted/removed? Read on!
So we recently ported our whole codebase from a custom SSR setup to a Nextjs based project. This specific case appeared in one module that gets fed a list of objects with properties that describe each object, which is usually a few default values, fields and validation functions. These validation functions are the properties that were getting removed during the run time. However, this was not always the case! While I was working on it, the module worked and gave the desired results. But, a simple change in the way we loaded the list of objects lead to the validation function properties being removed from the object. It seems the objects were now loaded inside the getInitialProps
lifecycle hook provided in next and then pass as a prop to the component whereas earlier the data was loaded in the render portion of the component itself.
It did not seem like a big deal but in Next.js getInitialProps
it is. It seems loading the data(list of objects) in getInitialProps
leads to the serialization
of the object, and so the function is removed from objects properties when the object is sent from the server to the client. Go ahead and try to serialize an object with a function as a property.
let obj = { a: 'some val', fun() { return true} };
JSON.stringify(obj);
If you run this piece of code in your browser console, you will notice that the functions are dropped in the serialization.
Oh, darn, then what do we do?
Well, All is not lost yet. You can convert the functions into strings that you want to preserve through serialization, as discussed in this StackOverflow answer.
Also, you can provide your own Stringification function to the JSON.stringify() function as a optional parameter. Here is a really good GitHub gist on the same.
See you next time.