LoginSignup
12
12

More than 5 years have passed since last update.

ネストしたオブジェクト/配列をImmutableに更新するためのJSのライブラリを書いた

Posted at

Immutable Update Patterns

ここあるように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みたいなものを使うのも一つの方法だろうけど、個人的にはオーバースペック。単純にネストした値を更新したいだけなんだ。いくつかそれっぽいライブラリがあったので見たけどイマイチいい感じのものがなかった。

ので自分で書いた。

hokaccha/immup

ざっくりこんな感じのことができる。

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);
      }
      //...
    }
  }
}

Source

12
12
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
12