Data Missing After JSON.stringify A Firebase Object
I have an app linked to firebase. When a user logs in, I assign his object firebase.auth().currentUser
to a variable. Then, I add a property (username
) to that variable . The thing is that when I console.log(currentUser)
I get the object with the added property. But, when I try to JSON.stringify
it then JSON.parse
it again (i do this to store it on localStorage
) I can't find my property username
that I added. What's happening here ?
var currentUser = firebase.auth().currentUser
currentUser.username = 'Foo';
console.log(currentUser) // => i get my prop username here
console.log(JSON.parse(JSON.stringify(currentUser))) // => i cant find my added prop here
Answer
currentUser
is not a plain object, it is an instance of the User class. As you can see, it implements a toJSON()
method which is automatically detected and used by JSON.stringify
as the canonical way to transform the object into JSON.
If you want to merge custom properties onto a Firebase user, you could just add toJSON()
first:
var currentUser = firebase.auth().currentUser.toJSON();
this will translate the User object into a plain object which would then be able to have additional properties added and still serialize as expected. Note, however, that this obviously won't persist on the user either server-side or on firebase.auth().currentUser
.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM