ここあるようにReactなどでオブジェクトや配列がネストしたstateを更新するのがひたすらめんどくさい。
function updateVeryNestedField(state, action) {
return {
....state,
first : {
...state.first,
second : {
...state.first.second,
[action.someId] : {
...state.first.second[action.someId],
fourth : action.someValue
}
}
}
}
}
正気の沙汰ではない。
Immutable.jsみたいなものを使うのも一つの方法だろうけど、個人的にはオーバースペック。単純にネストした値を更新したいだけなんだ。いくつかそれっぽいライブラリがあったので見たけどイマイチいい感じのものがなかった。
ので自分で書いた。
ざっくりこんな感じのことができる。
import immup from 'immup';
let state = {
todos: [
{ id: 1, title: 'foo', completed: true },
{ id: 2, title: 'bar', completed: false },
{ id: 3, title: 'baz', completed: false },
]
};
immup.set(state, 'todos.2.title', 'new title');
// =>
// {
// todos: [
// { id: 1, title: 'foo', completed: true },
// { id: 2, title: 'bar', completed: false },
// { id: 3, title: 'new title', completed: false },
// ]
// }
その他のAPIはドキュメントを参照のこと。
Bdashというアプリに組み込んでいい感じに使えている。
class QueryStore extends Store {
reduce(type, payload) {
switch (type) {
case 'selectQuery': {
let idx = this.findQueryIndex(payload.id);
return this
.set('selectedQueryId', payload.id)
.set('editor.line', null)
.merge(`queries.${idx}`, payload.query);
}
//...
}
}
}