Blog>
Snippets

Handling Redux Thunk Actions with ESM Syntax

Demonstrate creating and handling Redux thunk actions using ESM syntax, covering how to export and import thunks in a Redux application.
import { createAction, createAsyncThunk } from '@reduxjs/toolkit';

// Define a simple action creator
export const simpleAction = createAction('simple/action');

// Define an async thunk action
export const fetchUserData = createAsyncThunk(
  'user/fetchData',
  async (userId, thunkAPI) => {
    const response = await fetch(`https://api.example.com/users/${userId}`);
    const data = await response.json();
    if (response.ok) {
      return data;
    } else {
      return thunkAPI.rejectWithValue(data);
    }
  }
);
This code demonstrates how to define and export a simple action creator and an asynchronous thunk action using the Redux Toolkit and ESM syntax. The `simpleAction` is a regular action that can be dispatched normally. The `fetchUserData` thunk is an asynchronous action that performs an API request to fetch user data. It dispatches actions based on the promise's resolution or rejection.
import { configureStore } from '@reduxjs/toolkit';
import userReducer from './userSlice';

// Configure the Redux store
const store = configureStore({
  reducer: {
    user: userReducer
  },
  // Add Redux Thunk or other middleware if needed
  middleware: (getDefaultMiddleware) => getDefaultMiddleware()
});

export default store;
This code snippet shows how to configure a Redux store using the Redux Toolkit with ESM syntax. It imports the `userReducer` from another module and sets it as a reducer for the `user` slice of the application's state. The store configuration includes the default middleware, which has Redux Thunk enabled by default when using `configureStore`.
import { useSelector, useDispatch } from 'react-redux';
import { fetchUserData } from './userThunks';

// Component that dispatches the async thunk
const UserProfile = () => {
  const dispatch = useDispatch();
  const userId = useSelector(state => state.user.id);
  const userData = useSelector(state => state.user.data);
  
  useEffect(() => {
    if (userId) {
      dispatch(fetchUserData(userId));
    }
  }, [userId, dispatch]);

  return (
    <div>{userData && <p>{userData.name}</p>}</div>
  );
};

export default UserProfile;
This code snippet illustrates a React component (UserProfile) using hooks from 'react-redux' to interact with the Redux store. It dispatches the `fetchUserData` thunk using the `useDispatch` hook when the component mounts or when the `userId` changes. It also selects the user data from the store using the `useSelector` hook and conditionally renders it.