Blog>
Snippets

Implementing Asynchronous Actions

Illustrates handling asynchronous operations within TanStack Store, such as fetching data from an API and storing the response.
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import axios from 'axios';
Imports necessary functions and libraries. Here, axios is used for making the API request.
export const fetchUserData = createAsyncThunk(
  'users/fetchUserData',
  async (userId, thunkAPI) => {
    try {
      const response = await axios.get(`https://api.example.com/users/${userId}`);
      return response.data;
    } catch (error) {
      return thunkAPI.rejectWithValue('Failed to fetch user data.');
    }
  }
);
Defines an async action creator using createAsyncThunk. This function fetches user data from an API and handles both success and failure cases.
export const userSlice = createSlice({
  name: 'user',
  initialState: { data: null, loading: false, error: null },
  extraReducers: (builder) => {
    builder.addCase(fetchUserData.pending, (state) => {
      state.loading = true;
      state.error = null;
    });
    builder.addCase(fetchUserData.fulfilled, (state, action) => {
      state.loading = false;
      state.data = action.payload;
    });
    builder.addCase(fetchUserData.rejected, (state, action) => {
      state.loading = false;
      state.error = action.payload;
    });
  },
});
Creates a slice for user data with loading, success, and error states. It handles the lifecycle of the async action 'fetchUserData' using extraReducers.