LoginSignup
15
1

More than 5 years have passed since last update.

ImmutableとLodashでDynamoDBから取得した配列をソートする実装例。

Posted at

概要

ImmutableとLodashを使って配列を任意のキーでソートする機能の実装例を紹介します。前提としてAPI Gateway、Lambda、DynamoDBでサーバーレス構成を構築し、エンドポイントを叩けばソート前のデータが取得できる状態です。またModelの概念を取り入れ、ロジックはModelで持ち、Viewは描画のみを行うようにします。

やりたいこと

  • DynamoDBでGETしてきたデータの配列を任意のキーでソートして画面に表示する
  • Viewに直接ロジックを書きたくない

実装例

Modelの実装例です。Recordはプロパティやメソッドを持たせることができるので、Model実装に便利です。ソートに関してはLodashのorderByを使います。以下の例ではdata.sortのsortで配列をソートしています。return { Items: newDatas };の部分でソートした配列をItemsに入れてnewStateを返します。

models/item.js
import {
  Record,
  List,
} from 'immutable';

import _ from 'lodash';

const DatasRecord = Record({
  Count: '',
  Items: List(),
  ScannedCount: ''
});

const ItemState = Record({
  datas: DatasRecord()
});

class Item extends ItemState {

  sortByNum(state) {
    const newDatas = _.orderBy(state.datas.Items, (data) => {
      return data.sort;
    }, 'asc');


    const newState = state.update('datas',
      () => {
        return { Items: newDatas };
      });

    return newState;
  }
}

export default Item;

ソートの反映はボタン押下で実行できるようにします。

components/Hoge/SortButton/index.jsx
import React from 'react';

import PropTypes from 'prop-types';

import {
  Button,
} from 'semantic-ui-react';

class SortButton extends React.Component {
  static propTypes = {
    sortNum: PropTypes.func,
  }

  constructor(props) {
    super(props);

    this.handleSortBySortNumber = this.handleSortBySortNumber.bind(this);
  }

  handleSortBySortNumber() {
    this.props.sortNum();
  }

  render() {
      return (
        <div className="container">
          <Button
              basic
              color="teal"
              fluid
              onClick={this.handleSortBySortNumber}
            >
              ソート番号順
            </Button>
        </div>
      )
  }
}

export default SortButton;

View側は結果を描画するだけです。またkeyの指定が必要です。VirtualDOMのdiffからDOMに変更を反映させる時に最小限の変更に留めるためです。そのため、keyに指定するのは扱うリスト内でユニークなものである必要があります。

components/Hoge/Result.jsx
import React from 'react';

import PropTypes from 'prop-types';

import SortButton from './SortButton';


// Class Component
class Item extends React.Component {
  static propTypes = {
    hoge: PropTypes.object,
  }

  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    return (
      <div>

          {
            this.props.hoge.datas.Items.map((data) => {
              return (
                <div
                  key={data.Id}
                >
                  <div>
                    Name: {data.name}
                  </div>
                  <div>
                    SortNum: {data.sort}
                  </div>
                </div>
              );
            })
          }
              <SortButton
          {...this.props}
        />
      </div>
    );
  }
}

export default Item;

ソートをView側に書くことも可能ですが、どこに何が書いてあるのかメンテナンス上、管理が煩雑になることも考えられるので、ロジックなどはModelの概念を用いて管理するのもいいかと思います。

参考

公式
Immutable
Lodash orderBy
immutableのメリットとImmutable.jsでのModel定義

15
1
0

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
15
1