I have a React application where there is a page that creates clients, from there I send the data to createAsynkThank
of the Redux-Toolkit, which will handle the request and send it to the server where it will be saved in the DB (if the request is successful, it will be saved in the store).
I want in the event that the save fails for some reason, such as: that such a client already exists, or an invalid email, to send back to React an error and display it on the screen. Is it possible?
export const newClient = createAsyncThunk('clients/newClient',
async ({ name, email, tel }, { getState, dispatch, rejectWithValue }) => {
if (name && email && tel) {
$.post(`${URL}/clients/newClient`, { name, email, tel })
.then( res => {
dispatch(slice.actions.NewClient({ name, email, tel, _id: res.data.data._id }))
// return value success
})
.catch( err => {
// return value err
})
} else {
// return value
}
}
)
const setNewClient = () => {
dispatch(newClient({ name, email, tel }))
.then(res => console.log(res))
.catch(err => console.log(err))
}
Yes, you can return rejectWithValue
with the error.
Example:
export const newClient = createAsyncThunk(
'clients/newClient',
async ({ name, email, tel }, { getState, dispatch, rejectWithValue }) => {
try {
if (name && email && tel) {
const res = await $.post(
`${URL}/clients/newClient`,
{ name, email, tel }
);
dispatch(slice.actions.NewClient({
name,
email,
tel,
_id: res.data.data._id
}));
// return value success;
} else {
// return value
}
} catch(error) {
return rejectWithValue(error); // <-- return rejection w/error here
}
}
);
The UI should then unwrap the resolved Promise.
const setNewClient = async () => {
try {
const res = await dispatch(newClient({ name, email, tel })).unwrap();
console.log(res);
} catch(error) {
console.log(error);
}
}
or
const setNewClient = () => {
dispatch(newClient({ name, email, tel })).unwrap()
.then(res => console.log(res))
.catch(err => console.log(err));
};
For more details see: