0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[GraphQL] queryのwhere(条件)を動的に変更するよ

Posted at

インターンでqueryを動的に変更する場面があって少し悩んだのでメモとして置いておきます。
やりたかったことは、選択されたボタンによって条件を付け加えたり削除したりして動的にクエリを変えて表示されるものを変えたいって感じです。

query getProfile{
  profile( //ここ!!! ) {
   name,
   ...
  }
}

結論

とりあえず結果だけ先に示します。

const GET_MEMBERS = gql`
    query getProfile($title: [String!], $name: [String!]) {
      profile(where: {title: {_in: $title}, name: {_in: $name}}, order_by: {name: desc}){
        name
        ...
      }
    }
  `;

  const { data, loading, error } = useQuery(GET_MEMBERS,
    { variables: {
      name: name_selected.length === 0 ? name_all : name_selected,
      title: title_selected.length === 0 ? title_all : title_selected,
    } }
  );

注意するポイント

クエリの構造自体は静的な状態にしておく

初めはname:やら他のkeyやらを付けたり外したりしようかと考えたのですが、いろいろ調べてみるとクエリの構造を変数として持っちゃうといろいろ不都合があるみたいです。詳しくは以下のURLを参考に。なので、変数になるのはそれぞれのvalueになる部分のみです。
https://qiita.com/Quramy/items/fb579f60e29ccbda3c86

となると、選択されていない時は全て表示されて欲しいので、whereを使いながらも全てに当てはまるようにしなければいけないところが辛い。今回は

_in: {[]}

こういうことができない(当てはまるものがないとされる)から、予め検索条件が全て入った配列を用意することで対応させました。

型指定は必須

最初は静的なqueryだったので型指定をしていませんでしたが、variabelsを使う場合には型指定が必須になります。

($name: [String!])
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?