I have a Register component that sends a POST request to the API and if the registration is successful just show the user a notification and redirect to login page (for now). If not, the server sends back status 400 and a message. When I receive the response, I set a state variable serverError
to true and serverMessage
to whatever I received from the server to show it to the user.
POST Request logic:
export const registerRequest = (state, setState) => {
axios.post("api/auth/register", {
"email": state.email, "password": state.password, "firstName": state.firstName, "lastName": state.lastName
}).then((response) => {
if (response.status === 200) {
setState({
...state,
serverError: false
});
}
}).catch((exception) => {
setState({
...state,
serverMessage: exception.response.data,
serverError: true,
});
});
}
First I tried doing this "show user what's wrong" in the function dealing with form submit but I kept getting serverError === true
but serverMessage
being equal to an empty string (as declared in state). So next I tried using a componentDidUpdate
equivalent in useEffect
with the required dependencies and didMount
useRef
hook to make sure I show the notification only after the component is updated (i.e. after state update). Didn't work either.
useEffect
and handleSubmit
hook/function (useHistory
is from react-router-dom
and Notification
is an antD component that takes a title and a description):
const { serverError, serverMessage } = state;
const didMountRef = useRef(false);
useEffect(() => {
if (didMountRef.current) {
if (serverError) {
StyleImports.Notification["success"]({
message: [JsonImports.registerNotificationSuccess],
description: [JsonImports.registerSuccessDetails]
});
setTimeout(() => { history.push("/"); }, 4.5 * 1000);
}
else {
StyleImports.Notification["error"]({
message: [JsonImports.registerNotificationFail],
description: serverMessage
});
}
}
else didMountRef.current = true;
}, [serverError, serverMessage, history]);
const handleSubmit = (event) => {
// just some form validation logic before form submission
event.preventDefault();
registerRequest(state, setState);
// commented just to show you what I did initially
/*if (state.serverError) {
StyleImports.Notification["success"]({
message: [JsonImports.registerNotificationSuccess],
description: [JsonImports.registerSuccessDetails]
});
setTimeout(() => { history.push("/"); }, 4.5 * 1000);
}
else {
StyleImports.Notification["error"]({
message: [JsonImports.registerNotificationFail],
description: state.serverMessage
});
}*/
}
Any ideas on how to handle this properly? Just showing some message declared in a JSON client-side is not a good idea in my opinion since I can get different messages from the server. I guess setState
didn't actually update serverMessage
since it's a pretty big string and would take more time?