0%

Destructuring for Nested Object

Just begin my React learning path, noticed that destructure got used quite a lot, super handy, especially when we need to handle data which got passed from API.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function makeItem(){
return {
data: {
item:{
name: 'Shoes',
size: {
US: 10,
EU: 44
}
}
},
status: 'live'
}
}

const { data, status } = makeItem();

// to get items
const { data : { item }, status } = makeItem();
// then we cannot call data anymore, cause now we got item instead, data got destructured.

// can continue go even deeper
const { data : { item : { name, size } }, status } = makeItem();

// we can re-name them by using :
const { data : { createItem: item }} = await createItem();
// now createItem can be used by name of item
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function makeArrayOfItems() {
return {
data: {
items: [
{name: 'Shoes', price: 100},
{name: 'Shirt', price: 250},
]
},
status: 'live'
}
}

const { data: { items } } = makeArrayOfItems();
// use square-bracket notation instead of curly-bracket
const { data: { items: [ item1, item2 ] } } = makeArrayOfItems();

So neat, just beautiful. All examples come from WesBos.