Using createAsyncThunk with Reselect 5.0
Showcase how to create an asynchronous thunk action with Redux Thunk 3.0 and use Reselect 5.0 to memoize the result for optimized rendering.
import { createAsyncThunk } from '@reduxjs/toolkit';
import { createSelector } from 'reselect';
// Define an async thunk action
export const fetchData = createAsyncThunk(
'data/fetch',
async (arg, thunkAPI) => {
const response = await fetch('/some-api-endpoint');
const data = await response.json();
return data;
}
);
This piece of code imports the createAsyncThunk function from Redux Toolkit and the createSelector function from Reselect. It then defines an asynchronous thunk action called fetchData. This thunk makes a network request to '/some-api-endpoint', processes the response, and returns the result as a payload.
// State selector
const selectRawData = state => state.data;
// Memoized selector using Reselect for transforming raw data
export const selectTransformedData = createSelector(
[selectRawData],
(rawData) => {
// Transformation logic here
return transformedData;
}
);
This piece of code defines a basic selector called selectRawData which extracts the data part of the state. It uses createSelector from Reselect to create a memoized selector called selectTransformedData. This selector takes the raw data from selectRawData, applies some transformation logic, and returns the transformed data. The transformation logic is meant to be filled in where the comment indicates.