1
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 1 year has passed since last update.

RTK Thunk のfulfilled/rejected/pending関数

Posted at

RTK のcreateAsyncThunk にてfulfilled/rejected/pending が生成される。
これらは関数として実行できるのだが、ドキュメントに使い方がなさそうだったので手もとで動かしてみて確認してみた。

  • ポイント
    • thunk関数の引数の有無によって、actionの第3引数の有無も変わる
    • 各action+dispatch ごとに割り振られるrequestIDがあるが、これを明示的に割り当てないといけない

引数がないケース


export const thunkWithoutArgs = createAsyncThunk('thunkWithoutArgs', async () => {
  return 'actual return payload';
});

describe('async without args', () => {
  it('can create fulfilled', () => {
    const action = thunkWithoutArgs.fulfilled(
      'this is fake return payload',
      'this is fake request id',
    );
    expect(action).toEqual({
      meta: {
        arg: undefined,
        requestId: 'this is fake request id',
        requestStatus: 'fulfilled',
      },
      payload: 'this is fake return payload',
      type: 'thunkWithoutArgs/fulfilled',
    });
  });
});

引数があるケース

export const thunkWithArgs = createAsyncThunk('thunkWithArgs', async (arg1: string) => {
  return arg1 + ':actual return payload';
});

describe('async with args', () => {
  const action = thunkWithArgs.fulfilled(
    'this is fake return payload',
    'this is fake request id',
    'fake arg',
  );
  expect(action).toEqual({
    meta: {
      arg: 'fake arg',
      requestId: 'this is fake request id',
      requestStatus: 'fulfilled',
    },
    payload: 'this is fake return payload',
    type: 'thunkWithArgs/fulfilled',
  });
});

REF

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