Thursday, May 9, 2024
 Popular · Latest · Hot · Upcoming
62
rated 0 times [  67] [ 5]  / answers: 1 / hits: 10984  / 3 Years ago, sat, may 15, 2021, 12:00:00

How to reject properly with createAsyncThunk. I have an asynchronous function that checks whether a mail address already exists or not. The response of the function is an empty string if there is no registered mail address and the user object of the registered user if the user exists.


export const checkIfEmailExists = createAsyncThunk(
"user/checkIfEmailExists",
async (mail) => {
const response = await mailExists(mail).promise();
if (response.user && response.user.length > 0) {
reject();
} else {
resolve();
}
}
);

In both cases the data comes back and no error occurs. How do I reject the createAsyncThunk in such a case?


More From » redux

 Answers
7

You can use rejectWithValue to handle Thunk Errors.


E.g.


import {
configureStore,
createAsyncThunk,
createSlice,
} from '@reduxjs/toolkit';

function mailExists(mail) {
return {
async promise() {
// return { user: [{ name: 'teresa teng', mail }] };

return { user: [] };
},
};
}

export const checkIfEmailExists = createAsyncThunk(
'user/checkIfEmailExists',
async (mail: string, { rejectWithValue }) => {
const response = await mailExists(mail).promise();
if (response.user && response.user.length > 0) {
return response.user[0];
} else {
return rejectWithValue('No user found');
}
}
);

const userSlice = createSlice({
name: 'user',
initialState: {
data: {},
error: null,
},
reducers: {},
extraReducers: (builder) => {
builder
.addCase(checkIfEmailExists.fulfilled, (state: any, action) => {
state.data = action.payload;
})
.addCase(checkIfEmailExists.rejected, (state: any, action) => {
state.error = action.payload;
});
},
});

const store = configureStore({
reducer: {
user: userSlice.reducer,
},
});

store.dispatch(checkIfEmailExists('[email protected]')).then(() => {
console.log(store.getState());
});

Output of the console:


{ user: { data: {}, error: 'No user found' } }

[#1357] Friday, May 7, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
amari

Total Points: 736
Total Questions: 111
Total Answers: 90

Location: Saint Pierre and Miquelon
Member since Fri, Jan 28, 2022
2 Years ago
;