Hi i have a problem with my react app, I'm using useContext to parse my user to a voting site, but I have a small problem, my app is dobble loading, then my context turns to undefined, i can see the user at the first console.log but i cannot access it.
const { user, setUser } = useContext(UserContext)
const [medarbejdere, setMedarbejdere] = useState({})
const userLogIn = document.getElementById('id').value;
const user = medarbejdere?.filter(userid => userid.id === parseInt(userLogIn)).map(currentUser => console.log(currentUser))
setUser(user);
navigate("/votingsite")```
console.log is a void return, you are mapping a currentUser value to undefined and then updating likely the user state to an array of undefined values. Don't use Array.prototype.map for side-effects like console logging a value.
const { user, setUser } = useContext(UserContext);
const [medarbejdere, setMedarbejdere] = useState({});
const userLogIn = document.getElementById('id').value;
const user = medarbejdere?.filter(userid => userid.id === parseInt(userLogIn));
// console log the entire `user` array
console.log(user);
// or use `Array.protype.forEach` to issue side-effect on each element
user.forEach(currentUser => console.log(currentUser));
You also may be seeing the setUser and navigate calls as unintentional side-effects because they are in the component body. These should be in a callback or useEffect hook.
useEffect(() => {
setUser(user);
navigate("/votingsite");
}, []);
Related
first time userLogin successfully destructuring. but when i refresh page userLogin showing everithing in there but when i console uerInfo undefined. Why its heappening
function Header() {
const dispatch = useDispatch();
const userLogin = useSelector((state) => state.userLogin);
const { userInfo } = userLogin;
console.log(userLogin)// userInfo successfully showing
console.log(userInfo)//undefined
const logoutHandler = () => {
dispatch(logout());
};
I expecting the value of the object key successfully. Please Help
I have created this Auth Component and it works fine. Except that, It does not redirect if the unauthenticated user tries to visit /dashboard.
The backend upon receiving /api/me request, knows the user by having the cookie. So I have (Cookie-Session) Authentication technique.
export const UserContext = createContext();
const Auth = ({ children }) => {
const [user, setUser] = useState(null);
const [gotUser, setGotUser] = useState(false);
const navigate = useNavigate();
const getUser = async () => {
const res = await fetch('/api/me');
const data = await res.json();
setUser(data);
if (user) {
setGotUser(true);
}
};
useEffect(() => {
if (!gotUser) {
getUser();
}
}, [user, gotUser, navigate]);
if (!user) {
navigate('/login');
}
console.log(user);
return <UserContext.Provider value={user}>{children}</UserContext.Provider>;
};
So the main issue is that no redirection done. Also, The user passed to the context is not updated properly. Maybe because I am confused about what to use in useEffect .
Any help is appreciated.
Issues
There are a couple issues:
The "unauthenticated" state matches the "I don't know yet" state (i.e. the initial state value) and the component is redirecting too early. It should wait until the user state is confirmed.
The navigate function is called as an unintentional side-effect directly in the body of the component. Either move the navigate call into a useEffect hook or render the Navigate component to issue the imperative navigation action.
Solution
Use an undefined initial user state and explicitly check that prior to issuing navigation action or rendering the UserContext.Provider component.
const Auth = ({ children }) => {
const [user, setUser] = useState(); // <-- initially undefined
const navigate = useNavigate();
const getUser = async () => {
try {
const res = await fetch('/api/me');
const data = await res.json();
setUser(data); // <-- ensure defined, i.e. user object or null value
} catch (error) {
// handler error, set error state, etc...
setUser(null); // <-- set to null for no user
}
};
useEffect(() => {
if (user === undefined) {
getUser();
}
}, [user]);
if (user === undefined) {
return null; // <-- or loading indicator, spinner, etc
}
// No either redirect to log user in or render context provider and app
return user
? <Navigate to="/login" replace />
: <UserContext.Provider value={user}>{children}</UserContext.Provider>;
};
useEffect runs after your JSX is rendered, so as your code is made, on a page refresh this if (!user) that calls navigate('/login') will always pass, as before the useEffect does its work, user is null, that inital value you gave to useState. Yet it's not redirecting because navigate does not work inside JSX, it should be replaced with Navigate the component.
Also, in getUser, you have this if (user) juste after setUser(data), that wouldn't work well as user won't get updated immediately, as updating a state is an asynchronous task which takes effect after a re-redner .
To fix your problems you can add a checking state, return some loader while the user is being verified. Also you can optimise a little bit your code overall, like getting ride of that gotUser state:
export const UserContext = createContext();
const Auth = ({ children }) => {
const [user, setUser] = useState(null);
const [checking, setChecking] = useState(true);
const getUser = async () => {
try {
const res = await fetch("/api/me");
const data = await res.json();
setUser(data);
} catch (error) {
setUser(null);
} finally {
setChecking(false);
}
};
useEffect(() => {
if (!user) {
getUser();
}
}, [user]);
if (checking) {
return <p>Checking...</p>;
}
if (!user) {
return <Navigate to="/login" replace />
}
return <UserContext.Provider value={user}>{children}</UserContext.Provider>;
};
export default Auth;
I am using React-native and in it, I have a custom Hook called useUser that gets the user's information from AWS Amplify using the Auth.getUserInfro method, and then gets part of the returned object and sets a state variable with it. I also have another Hook called useData hook that fetches some data based on the userId and sets it to a state variable.
useUser custom-Hook:
import React, { useState, useEffect } from "react";
import { Auth } from "aws-amplify";
const getUserInfo = async () => {
try {
const userInfo = await Auth.currentUserInfo();
const userId = userInfo?.attributes?.sub;
return userId;
} catch (e) {
console.log("Failed to get the AuthUserId", e);
}
};
const useUserId = () => {
const [id, setId] = useState("");
useEffect(() => {
getUserInfo().then((userId) => {
setId(userId);
});
}, []);
return id;
};
export default useUserId;
import useUserId from "./UseUserId";
// ...rest of the necessary imports
const fetchData = async (userId) = > { // code to fetch data from GraphQl}
const useData = () => {
const [data, setData] = useState();
useEffect(() => {
const userId = useUser();
fetchData(userId).then( // the rest of the code to set the state variable data.)
},[])
return data
}
When I try to do this I get an error telling me
*Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.*
I think the problem is that I am calling the Hook useUser inside of the use effect, but using it inside the function will cause the problem described here, and I can't use it outside the body of the fetchData since the useData itself is a hook, and it can be only used inside a functional component's or Hook's body. So I don't know how to find a way around this problem.
Correct, React hooks can only be called from React function components and other React hooks. The useEffect hook's callback isn't a React hook, it's a callback. According to the Rules of Hooks, don't call hooks inside loops, conditions, or nested functions.
I suggest refactoring the useData hook to consume the userId as an argument, to be used in the dependency array of the useEffect.
const fetchData = async (userId) => {
// code to fetch data from GraphQl
};
const useData = (userId) => {
const [data, setData] = useState();
useEffect(() => {
fetchData(userId)
.then((....) => {
// the rest of the code to set the state variable data.
});
}, [userId]);
return data;
};
Usage in Function component:
const userId = useUser();
const data = useData(userId);
If this is something that is commonly paired, abstract into a single hook:
const useGetUserData = () => {
const userId = useUser();
const data = useData(userId);
return data;
};
...
const data = useGetUserData();
Though you should probably just implement as a single hook as follows:
const useGetUserData = () => {
const [data, setData] = useState();
useEffect(() => {
getUserInfo()
.then(fetchData) // shortened (userId) => fetchData(userId)
.then((....) => {
// the rest of the code to set the state variable data.
setData(....);
});
}, []);
return data;
};
You can't call hook inside useEffect, Hook should be always inside componet body not inside inner function/hook body.
import useUserId from "./UseUserId";
// ...rest of the necessary imports
const fetchData = async (userId) => {
// code to fetch data from GraphQl}
};
const useData = () => {
const [data, setData] = useState();
const userId = useUser();
useEffect(() => {
if (userId) {
fetchData(userId).then(setData);
}
}, [userId]);
return data;
};
Hello so am trying to make a custom hook where i get my user object from database and using it however my console log shows the the object is undefined shortly after object appears and this effect other function relying on it they only capture the first state and gives an error how can i fix that here is my code for the hook:-
import { useState, useEffect } from 'react'
import { storage, auth, database } from '../api/auth';
export default function useUser() {
const [user, setUser] = useState()
const userId = auth.currentUser.uid;
useEffect(() => {
getCurrentUser();
}, [])
const getCurrentUser = () => {
database.ref("users/" + userId).orderByChild('name').once("value").then(snapshot => {
setUser(snapshot.val())
})
}
return user
}
First of all you can assign default value to userObject.
const [user, setUser] = useState(null);
After place where you use useUser hook you can make a check is it null or not.
const user = useUser();
if (!user) {
return <Text>Loading...</Text>;
}
return(
<Text>{user.name}</Text>
);
I have a method which would use the value from useSelector and another dispatch which would update my value from the useSelector, however, it seems the value does not get updated after dispatch, for example
const userProfile = (props) => {
const hasValidationError = useSelector(state => {
state.hasValidationError;
}
const dispatch = useDispatch():
const updateProfile = async (userId) => {
dispatch(startValidation()); // <-- this would change the hasValidationError in state
if (hasValidationError) {
console.log('should not update user');
await updateUser(userId);
dispatch(showSuccessMsg());
} else {
conosole.log('can update user');
}
}
}
The hasValidationError would always be false, even if the value did changed from state, how could I get the updated value immediately after dispatch(startValidation()) ?
I also tried something different, like creating a local state value to monitor my global state by using useState() and useEffect()
const [canUpdateUser, setCanUpdateUser] = useState(false);
useEffect(() => {
console.log('useEffect hasValidationError :>> ', hasValidationError);
setCanUpdateUser(!hasValidationError);
}, [hasValidationError]);
Then use canUpdateUser as my conditional flag in updateProfile (if (canUpdateUser)), however, this seems to work only the first time when validation triggers, but after that, the canUpdateUser value is always the old value from my updateProfile again...
How could I resolve this? Is there any way to ensure getting updated value from global state after certain dispatch fires?
Could you maybe try from a slightly different approach (combining both) since it seems you want to be listening on changes of hasValidationError, using a useEffect with a dependency on that variable can maybe resolve your issue.
const userProfile = (props) => {
const { hasValidationError } = useSelector(state => state);
const dispatch = useDispatch():
const [userId, setUserId] = useState();
const updateProfile = async (userId) => {
dispatch(startValidation());
setUserId(userId);
};
useEffect(() => {
if (hasValidationError) {
console.log('should not update user');
await updateUser(userId);
dispatch(showSuccessMsg());
} else {
conosole.log('can update user');
}
}, [hasValidationError]);
}