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?

APIレスポンスの一部だけを変更する方法(バックエンド未対応項目をフロントで補完)

0
Posted at

目次

はじめに

バックエンド側でAPIが未実装で、フロントエンド側で仮実装を行って動作確認を行いたい場合があります。

APIレスポンスの一部だけを変更する方法について記載します。

修正前

既存のコードが

async detail(): Promise<UserDetailApiResponse> {
   const response = await this.axiosClient.get(`${this.endpoint}/user/detail`);
   return response.data;
}

となっており、以下のようにResponseが返却されるとします。

APIレスポンスの例

やりたいこと

result.user.infoに "importantNotification" : 1 を追加したい。

修正後

async detail(): Promise<UserDetailApiResponse> {
const response = await this.axiosClient.get(`${this.endpoint}/detail`);
const data: UserDetailApiResponse = response.data;

if (data.result?.user?.info?.importantNotification == null) {
  return {
    ...data,
    result: {
      ...data.result,
      user: {
        ...data.result.user,
        info: {
          ...data.result.user.info,
          importantNotification: 1, // 仮で1を設定
        },
      },
    },
  };
}

return data;
}

解説

図にすると

data
│
├─ status = 200
└─ result
    │
    └─ user
        │
        └─ info
            ├─ user_name = "白石 飛鳥"
            ├─ mail_address = "shiraishi_asuka@nogizaka.com"
            ├─ notification = 0
            └─ importantNotification = undefined

 ↓↓

コピーして一部だけ書き換えする

data
│
├─ status = 200      ←そのまま
└─ result            ←コピー
    │
    └─ user          ←コピー
        │
        └─ info      ←コピー
            ├─ user_name = "白石 飛鳥"
            ├─ mail_address = "shiraishi_asuka@nogizaka.com"
            ├─ notification = 0
            └─ importantNotification = 1 ← これを追加したい

となっています。
すなわち元のデータをそのままコピーし、importantNotificationだけを書き換えています。

スプレッド構文が多用されている理由

修正後のコードでは、...dataや...data.result.userのように、スプレッド構文 (...) が使われています。

なぜ

data.result.user.info.reportsNotification = 1;

ではダメなのか?

たしかにdata.result.user.info.reportsNotification = 1;でも値は変えられますが、元のdata自体を書き換えてしまうため、副作用(思わぬ影響)の原因になることがあります。

そのため、

return {
  ...data,
  ...
}

と記述し、スプレッド構文 (...)を利用して新しいオブジェクトを作っています。

ミュータブルとイミュータブル

  • ミュータブル(Mutable):可変。変更可能な変数の型。
    既存のデータを書き換えることができる。
    JavaScriptではオブジェクトと配列だけがミュータブル。
  • イミュータブル(Immutable):不変。新しい値を作成しない限り、その内容を変更することができない値。
    一度作ったデータを変更せず、新しいデータを作ることができる。

スプレッド構文は、オブジェクトをイミュータブルに扱いたい場合に使われることがあります。

修正後のコードは、元のオブジェクトを直接変更しない書き方になります。

参考サイト

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?