React/React Context API: Wait for context values when using useEffect() hook

試著忘記壹切 提交于 2021-01-28 08:01:44

问题


I am developing a web app using React and here is what I am trying to do:

  1. In the highest-order component, check whether the user is logged in and if logged in, update 'userinfo' Context value.
  2. In Profile.js, get the 'userinfo' Context value.
  3. Check whether 'userinfo' is null or not, and call different APIs accordingly.

I wrote the below code. The problem is that there is apparently a time lag for the userinfo context value to be delivered to the component. So when using useEffect() hook, Profile.js will render twice when userinfo is not null.

Is there a way to fix this code so that it waits for 'userinfo' variable, and then call relevant APIs accordingly, not before?

Below is the code. Any advice? Thanks a lot in advance!

import React, {useEffect, useContext} from 'react';
import Userinfo from "../context/Userinfo";


function Profile(props) {

   const {userinfo, setuserinfo}=useContext(Userinfo);

   useEffect(()=>{      
       ((userinfo==null)?
       /*API call A (When user is not logged in) */ :
       /*API call B (When user is logged in) */
       )},[userinfo])  

   return (
       (userinfo==null)?
       /*Elements to render when user is not logged in) */ :
       /*Elements to render when user is  logged in) */
   );
}

export default Profile;

回答1:


The best solution here is to add a loading state in the context provider which is reset once the value is updated.

function Profile(props) {

   const {userinfo, loading, setuserinfo}=useContext(Userinfo);

   useEffect(()=>{      
       if(!loading) {
            ((userinfo==null)?
             /*API call A (When user is not logged in) */ :
            /*API call B (When user is logged in) */
            )
       }
    )},[loading, userinfo])  

   if(loading) return <Loader />
   return (
       (userinfo==null)?
       /*Elements to render when user is not logged in) */ :
       /*Elements to render when user is  logged in) */
   );
}



回答2:


I have this problem today, I like what Shubham does. But the way I solve it is just getting the userinfo from the previous component and pass it to this profile component.

However, make sure you render the Profile component like this so that you can make sure the userinfo exists:

function ParentComponent(){
 // do sth to get the userinfo here
return(
  <ParentComponent>
     {userinfo? <Profile userinfo={userinfo} /> : null}       
 <ParentComponent/>
)
}


来源:https://stackoverflow.com/questions/61479097/react-react-context-api-wait-for-context-values-when-using-useeffect-hook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!