first of all, I am newbie in both StackOverFlow and coding ^^.
Here are some global informations :
- BACKEND : Rails 7.0.4 / ruby 3.1.2
- FRONTEND : Node v18.18.2 (React)
Here is my goal which is pretty simple :
- getting user data from an authentication request towards the backend API.
- setting these user data in the local storage (through Jotai atomWithStorage).
The bug is that the data setting by Jotai setAuthUserData(data) is not triggering components re-render.
Here is the signIn function :
// Function to login to backend
export const signIn = (
login,
password,
setAuthUserData,
setPreauditAnswers,
setAuthenticationFailed,
navigate,
setIsSigninLoading,
currentURL,
setSelectedTool
// setIsPreauditSelected,
// setIsSupplierAssesmentSelected,
// setIsAuditRGPDSelected
) => {
setIsSigninLoading(true);
fetch(process.env.REACT_APP_BACKEND_URL + "users/sign_in", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
user: {
email: login,
password: password,
},
}),
})
.then((response) => {
// console.log("RESPONSE from SIGN IN :\n", response);
if (response.headers.get("Authorization")) {
const expirationDate = new Date();
expirationDate.setFullYear(expirationDate.getFullYear() + 1);
response.headers.get("Authorization") &&
Cookies.set(
process.env.REACT_APP_SESSION_COOKIE_NAME,
response.headers.get("Authorization"),
{
expires: expirationDate,
sameSite: "None",
secure: true,
}
);
} else {
setAuthenticationFailed(true);
}
setIsSigninLoading(false);
return response.json();
})
.then((data) => {
// console.log("DATA from SIGN IN :\n", data);
if (data.message === "You are logged in.") {
setAuthUserData(data); //Here is the line not working as I expect
setPreauditAnswers(data.user_preaudit);
redirectUserOnTheRightTool(
currentURL,
setSelectedTool,
data.is_user_admin
);
}
});
// .catch(error => console.error("SignIn -> ERROR", error.message))
};
Here is the atom declaration :
import { atomWithStorage } from "jotai/utils";
export const authenticationAtom = atomWithStorage("authenticationData");
I see that the local storage is updated after signing in, because if I refresh the user account page, all informations are displayed as expected.
What I tried is : I made tests in an other component (the header) :
- create a button that do setAuthUserData("a value")
- create a button that do setAuthUserData(null)
What I wanted to check through these tests is wether the value of the atom changes or not by clicking on each button from an other component, and it changes as expected.
I also tried to set the value of a different atom in the signIn function (provided) in order to check if the problem is global over all atoms. But I could see that it is not global as values are correctly updated for other atoms.
Hope I have been clear enough :)
Have a good and thanks for reading.
Julien