score:1
notes:
1. this code will error if sessiondata
is null
or undefined
:
const [{sessiondata: { user }}, loading] = usesession();
const usesession = () => [{
expires: new date(date.now() + (3600 * 1000 * 24)),
sessiondata: null
}, false];
const [{ sessiondata: {user}}, loading] = usesession();
console.log('user:', user, 'loading:', loading);
2. using the same code, you can't assign an inline default value to fix the typeerror
described above.
const somedata = {
foo: 'foo',
bar: 'bar'
};
//assign `baz: 'default'` to avoid `typeerror` if `baz` property does not exist
const {foo, bar, baz = 'default'} = somedata;
console.log(foo, bar, baz);
//sadly, this doesnt work here.
const usesession = () => [{
expires: new date(date.now() + (3600 * 1000 * 24)),
sessiondata: null
}, false];
const [{ sessiondata: {user} = {} }, loading] = usesession();
console.log('user:', user, 'loading:', loading);
maybe i'm missing something but i just can't get it to work using default values. the only way i fixed this is getting sessiondata
first then work on that afterwards while using default values.
const usesession = () => [{
expires: new date(date.now() + (3600 * 1000 * 24)),
sessiondata: null
}, false];
//assign {} to `sessiondata` if it is undefined
const [{expires, sessiondata = {} }, loading] = usesession();
console.log(sessiondata); //null
//above default value will still fail if sessiondata is null.
// to fix, coalesce to {}
const {user, token} = sessiondata || {};
console.log(user, token);
3. be careful with "gotcha's"
you may have noticed the || {}
code in the above code even though we added a default value to sessiondata
. this is because default values only apply to undefined
, not null
s.
on the same note, it is better to add a coalesce on usesession
too since your code will break if usesession()
returns a null
or undefined
.
const usesession = () => { return null; };
//assign {} to `sessiondata` if it is undefined
console.log(usesession()); //null
// usesession()[0], a.k.a. session is undefined
// need to add default since we are destructuring `sessiondata` from `session`
const [{ sessiondata } = {}, loading] = usesession() || [];
//// this also works but it assigns `sessiondata = {}`
//const [{ sessiondata = {} } = {}, loading] = usesession() || [];
// wont be doing that since we are proving the next point:
//above default value will still fail since `sessiondata` will be undefined
// to fix, coalesce to {}
const {user, token} = sessiondata || {};
console.log(user, token);
finally
getting sessiondata
and/or expires
(a.k.a session
) first actually isn't bad at all since you may also want to get the other properties, i.e, session.expires
, sessiondata.token
, etc. it also allows you to fix the gotchas mentioned above.
this awesome article (object destructuring best practice in javascript) discusses the above notes in-depth. take time to read.
score:0
the object structure you provided is not valid. i came to get user
and token
with following construct:
var a = {
session: {
expires: '1d',
sessiondata: {
user: 'myuser',
token: 'token'
}
}
}
var {session: {sessiondata: {user, token}, expires}} = a
console.log(user, token, expires) // 'myuser token 1d'
for more info, see es6 deep nested object destructuring
score:1
you can destructure like this to set the user
variable:
const [{sessiondata: { user }}, loading] = usesession();
Source: stackoverflow.com
Related Query
- Destructuring a Object nested inside Array
- update nested state object with array inside
- How can I render the contents of an array nested inside an object in React Admin's show/ArrayField component?
- How can I access JSON property of nested object inside object array
- How to add new element to array which inside nested object by its path?
- How to push inside nested array of object that have a precise value of a key in MongoDB?
- Setting nested array inside object in ReactJS
- Update state of array nested inside object (ReactJS)
- how to iterate through nested object which is inside an array in javascript
- How to push an object inside nested array using React and TypeScript?
- How to change nested object value inside of an array in JavaScript?
- Updating property inside a nested array of object
- How to add a new object to an array of objects that is nested inside an array of objects in ReactJS?
- How can I access a nested object inside an array to validate it?
- ReactJS updating a single object inside a state array
- ES6 Object Destructuring Default Values for Nested Parameters
- delete an object in a nested array which has key value
- How to setState of nested JSON array object of mapped input
- How to count multiple objects inside nested array sequentially in react js
- ReactJS: Updating array inside object state doesn't trigger re-render
- Push item to a nested object array
- How to remove an element from an array that is inside an object in React JS (ES6)
- Changing state of object nested in array of objects
- How to delete nested state object in immutable-js inside reducer?
- React Hooks - Why array destructuring over object destructuring?
- How delete an object based on its index from a nested array in React?
- Iterate through a nested json object array in the render (ReactJS)
- Targeting nested object properties inside an parent object
- How to iterate over an array that's inside an object in React JS
- How to implement a Search inside a Nested Array of Objects?
More Query from same tag
- How to transpile and minify single file with webpack?
- Unable to mock onKeyPress enter on input
- Babel throws a syntax error on arrow function
- I'm getting error when manipulating array
- Displaying list dynamically in react when user click on input filed
- "this" avaialable but "this.state" not available
- Context Provider not working in Next with Typescript
- Mapping Double nested JSON - Object not allowed in React Child
- How to implement react routing with bootstrap navbar component?
- pass value of object created when document loads into a variable in react
- Add a class to child component when parent component state changes
- Can the default value of a recoil atom be an object of objects?
- React pass using useNavigate cannot read properties of null
- react-router-Dom: Blank page after redirect multiple user on login in React
- How to map nested array in gatsby with reactjs and graphql
- Width changes in material-ui TextField when label shrinks
- createMemoryHistory still reports `Browser history needs a DOM`
- Sentry - React - capture errors iframe and only iframe
- Return promise from Fetch when posting through Nodemailer
- Trying to save value to redux store - getting dispatch is not a function
- React Router work on reload, but not when clicking on a link
- Render table data with head in each row in React
- Make Multiple Post Requests In Axios then get all the response to make another request
- How do I automatically create a new element upon submission of an input in ReactJs
- Massive spike in YouTube Data API queries
- React: unable to fetch state inside setInterval
- React Pagination Styling
- How to Keep active state of an item inside of component that iterates over some dataset
- How can i can change the value of a variable with if/else to return certain div in react
- React/Redux mapStateToProps by ownProps