0

one quick question, is it ok to use the same label for my asyncthunk setup ? in my SS it shown as fetchFOrmData - users/fetchFormData since in the doc it always shown as different label

enter image description here

enter image description here

Lin Du
  • 88,126
  • 95
  • 281
  • 483
rionalab
  • 42
  • 5

1 Answers1

1

This is an opinion-based question.

First, we should know the recommended naming convention for the redux action type. See Write Action Types as domain/eventName

we suggest using the "domain/action" convention for readability.

Personally, I prefer keeping the thunk name the same as the action part of domain/action.

E.g.

users.slice.ts:

import { createAsyncThunk } from '@reduxjs/toolkit';

export const fetchAllUsers = createAsyncThunk('users/fetchAllUsers', () => []);
export const fetchUserById = createAsyncThunk('users/fetchUserById', () => ({}));

locations.slice.ts:

import { createAsyncThunk } from '@reduxjs/toolkit';

export const fetchAllLocations = createAsyncThunk('locations/fetchAllLocations', () => []);
export const fetchLocationById = createAsyncThunk('locations/fetchLocationById', () => ({}));

main.ts:

import { fetchLocationById, fetchAllLocations } from './location.slice';
import { fetchUserById, fetchAllUsers } from './user.slice';

function main() {
  fetchUserById();
  fetchAllUsers();

  fetchLocationById();
  fetchAllLocations();
}

There are several advantages:

  1. If we use fetchAll, we have to use namespace import (import * as usersSlice from './users.slice.ts') or import alias. Otherwise, the fetchAll of the user slice and location slice will be in conflict.
import * as userSlice from './user.slice';
import * as locationSlice from './location.slice';

function main() {
  userSlice.fetchAll();
  userSlice.fetchById();

  locationSlice.fetchAll();
  locationSlice.fetchById();
}
  1. When we search globally in the editor or IDE, fetchAllUsers will be more accurate and have fewer search results than fetchAll.

  2. We don't need to map between the action type(users/fetchAllUsers) and the thunk name(fetchAllUsers) when reading the code and debug.

I have seen many projects keep the thunk name the same as the action type name.

grafana uses this naming convension.

Lin Du
  • 88,126
  • 95
  • 281
  • 483