ReasonJun

Redux : createAsyncThunk 본문

Frontend/Redux

Redux : createAsyncThunk

ReasonJun 2023. 8. 20. 02:06
728x90

createAsyncThunk is a function in Redux Toolkit that helps you write asynchronous actions in Redux. Asynchronous actions are actions that perform some kind of external operation, such as fetching data from an API.

 

createAsyncThunk takes two arguments:

  • actionName: The name of the action.
  • payloadCreator: A function that takes the action's payload as an argument and returns a promise.

The payloadCreator function is where you would write the code to perform the asynchronous operation. For example, the following code creates an asynchronous action called fetchUsers that fetches a list of users from an API:

const fetchUsers = createAsyncThunk('fetchUsers', async () => {
  const response = await fetch('<https://api.example.com/users>');
  const users = await response.json();
  return users;
});

The fetchUsers action will dispatch three actions:

  • fetchUsersPending: This action is dispatched when the fetchUsers action is first dispatched.
  • fetchUsersFulfilled: This action is dispatched when the fetchUsers action successfully completes. The action's payload will be the result of the asynchronous operation.
  • fetchUsersRejected: This action is dispatched when the fetchUsers action fails. The action's payload will be an error object.

The createAsyncThunk function is a powerful tool that can help you write more concise and maintainable Redux code for asynchronous actions. It is recommended for most projects.

 

Here are some of the benefits of using createAsyncThunk:

  • It makes your code more concise and readable.
  • It helps you to test your Redux code more easily.
  • It makes it easier to manage large state trees.
728x90

'Frontend > Redux' 카테고리의 다른 글

Redux : toolkit : persistReducer & persistStore  (0) 2023.08.20
Redux : toolkit : abort()  (0) 2023.08.20
Redux : toolkit : createAction / createReducer  (0) 2023.08.19
Redux : toolkit API : configureStore()  (0) 2023.08.19
Redux: toolkit  (0) 2023.08.19
Comments