New to React Hooks and unsure how to solve. I have the following snippet of code within my App.js file below.
What I am basically trying to achieve is to get the user logged in by calling the getUser()
function and once I have the user id, then check if they are an authorised user by calling the function checkUserAccess()
for user id.
Based on results within the the validIds
array, I check to see if it’s true or false and set authorised state to true or false via the setAuthorised()
call.
My problem is, I need this to process first prior to performing my first render within my App.js file.
At the moment, it’s saying that I’m not authroised even though I am.
Can anyone pls assist with what I am doing wrong as I need to ensure that authorised
useState is set correctly prior to first component render of application, i.e. path=”/”
const [theId, setTheId] = useState(''); const [authorised, setAuthorised] = useState(false); const checkUserAccess = async (empid) => { try { const response = await fetch("http://localhost:4200/get-valid-users"); const allUsers = await response.json(); const validIds = allUsers.map(({ id }) => id); const isAuthorised = validIds.includes(empid); if (isAuthorised) { setAuthorised(true) } else { setAuthorised(false) } } catch (err) { console.error(err.message); } } const getUser = async () => { try { const response = await fetch("http://localhost:4200/get-user"); const theId= await response.json(); setTheId(theId); checkUserAccess(theId); } catch (err) { console.error(err.message); } } useEffect(() => { getUser(); }, []);
Advertisement
Answer
Unless you are wanting to partially render when you get the user ID, and then get the access level. There is no reason to have multiple useState’s / useEffect’s.
Just get your user and then get your access level and use that.
Below is an example.
const [user, setUser] = useState(null); const checkUserAccess = async (empid) => { const response = await fetch("http://localhost:4200/get-valid-users"); const allUsers = await response.json(); const validIds = allUsers.map(({ id }) => id); const isAuthorised = validIds.includes(empid); return isAuthorised; } const getUser = async () => { try { const response = await fetch("http://localhost:4200/get-user"); const theId= await response.json(); const access = await checkUserAccess(theId); setUser({ theId, access }); } catch (err) { console.error(err.message); } } useEffect(() => { getUser(); }, []); if (!user) return <div>Loading</div>; return <>{user.theId}</>