Skip to content

Instantly share code, notes, and snippets.

@wuct
Last active August 29, 2015 14:27
Show Gist options
  • Save wuct/b7d1c8e014e9c7d9a45b to your computer and use it in GitHub Desktop.
Save wuct/b7d1c8e014e9c7d9a45b to your computer and use it in GitHub Desktop.
// get users list (array), convert it to object
users = users.reduce((res, user) => {
res[user.id] = user;
return res;
}, {})
// which will look like
users = {
'123': {},
'124': {}
};
// get user/123 (detail about this user), merge it
const users = {
...users,
...{ '123': user }
}
// get user/123/friends (another users array)
// first extract friend ids
friendIds = friends.map(user=>user.id)
// then convert friends to an object,
users = {
...users,
...friends,
...{ '123': { ...users[123], friendIds }}
}
// or users[123] = { ...users[123], ...{friendIds: friends.map(user=>user.id)}};
@wuct
Copy link
Author

wuct commented Aug 12, 2015

根本問題是 Restful API 跟 immutabel 不合啊

@rayshih
Copy link

rayshih commented Aug 12, 2015

沒這麼誇張到不合吧?
資料格式不一樣而已
一個是 array index
一個是 id index
你做的事情只不過是把前者轉後者而已
沒什麼太大差別

@wuct
Copy link
Author

wuct commented Aug 12, 2015

對我而言 mindset 差很多啊。如果用 array 的話,當 friends 進來的時候會傾向再開一個新 array,而不是 merge 進 users;如果又有其他 users 相關的 list,array 就會愈開愈多,這樣你的 single store 就會愈長愈怪。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment