After logging in the users profile details will only update once the page is refreshed.
I am using the MERN stack for this application.
For the useEffect, I have tried it with empty square brackets, without any brackets and with userData and user inside the brackets to test if it would work when the user or user data was updated but this did not work.
User Details Context:
const UserDetailsContext = createContext();
export function UserDetailsProvider({ children }) {
const { user, setUser } = useUserContext();
const [userData, setUserData] = useState({
firstName: "",
lastName: "",
email: "",
phoneNumber: "",
location: "",
});
useEffect(() => {
const data = getUser2().then((res) => {
setUserData({
firstName: res.firstName,
lastName: res.lastName,
email: res.email,
phoneNumber: res.phoneNumber,
location: res.location,
});
});
return () => data;
}, [userData]);
App.js:
export default function App() {
const route = useNavigate();
const [user, setUser] = useState(null);
useEffect(() => {
const unsubscribe = getUser()
.then((res) => {
if (res.error) return console.log(res.error);
else setUser(res.username);
})
.catch((err) => console.log(err));
return () => unsubscribe();
}, [])};
I’m running this controller at 2 different points, once when the user logins in and the username updates. This is working fine, then another in my context using a different API and server route to update the form data, not sure if this is correct as only newly starting React.
Controller:
exports.getLoggedInUser = (req, res) => {
return res.status(200).json({
message: "User is still logged in",
firstName: req.user.firstName,
lastName: req.user.lastName,
email: req.user.email,
location: req.user.location,
phoneNumber: req.user.phoneNumber,
username: req.user.username,
});
};
2
Answers
I got it working by changing the state to an object and updating the state once the user is updated like below -
Not sure what’s happening, but the useEffect only re-runs if the below conditions are all correct:
and of course when you refresh, it runs anyway.