Search code examples
reduxredux-toolkit

Is it possible to put repetitive code logic into a separate function in createAsyncThunk (Redux Toolkit)?


I have an application structure. Example:

  • entities/user/services/checkAuth
  • features/auth-user/services/login (registration, logout, refresh)

Examples of service (1):

export const refreshService = createAsyncThunk<void>(
    'auth-user/refreshService',
    async (_, thunkAPI) => {
        try {
            const response = await axios.get<AuthResponse>('http://localhost:4000/api/refresh', { withCredentials: true })
            const { tokens, user } = response.data

            thunkAPI.dispatch(userActions.setData(user))
            thunkAPI.dispatch(userActions.authorize())
            localStorage.setItem(USER_ACCESS_TOKEN, tokens.accessToken)
        }
        catch (error) {
            ...
        }
    },
)

Examples of service (2):

export const refreshService = createAsyncThunk<UserEntity, RegistrationRequest>(
    'auth-user/registrationService',
    async (data, thunkAPI) => {
        try {
            const response = await axios.post<AuthResponse>('http://localhost:4000/api/registration', data)

            if (!response.data) {
                throw new Error()
            }

            const { user, tokens } = response.data

            thunkAPI.dispatch(userActions.setData(user))
            thunkAPI.dispatch(userActions.authorize())
            localStorage.setItem(USER_ACCESS_TOKEN, tokens.accessToken)

            return user
        }
        catch (error) {
            ...
        }
    },
)

In many of them this code section is repeated:

thunkAPI.dispatch(userActions.setData(user))
thunkAPI.dispatch(userActions.authorize())
localStorage.setItem(USER_ACCESS_TOKEN, tokens.accessToken)

Is there a way to reuse this functionality in the Redux Toolkit?


Solution

  • I tried putting the code in a separate function and it seems to work:

    export const handleAuthResponse = (
        thunkAPI: GetThunkAPI<AsyncThunkConfig>,
        user: UserEntity,
        tokens: TokenEntity,
    ) => {
        thunkAPI.dispatch(userActions.setData(user))
        thunkAPI.dispatch(userActions.authorize())
        localStorage.setItem(USER_ACCESS_TOKEN, tokens.accessToken)
    }
    

    Usage:

    try {
        const response = await axios.get<AuthResponse>('http://localhost:4000/api/refresh', {
                    withCredentials: true,
         })
    
        const { user, tokens } = response.data
    
        handleAuthResponse(thunkAPI, user, tokens)
     }