Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

reactjs - React set provider variables on application load

In the root of my app I need to make calls to an api when the app loads and use that data in the provider.

const App = () => {
  const [userRoles] = useState(['SuperUser']);
  const [selectedProfileId, setSelectedProfileId] = useState(null);

  const { isLoading, user, error } = useAuth0();
  const { data, loading: profileLoading, error: profileError } = useQuery(
    GET_PROFILES
  );


  useEffect(() => {
    setProfileId(data?.items?.[0]?.id);
  }, [data]);

  if (isLoading || profileLoading) return <Loading />;

  if (error)
    return (
      <Alert />
    );

  if (searchCustomersError) {
    return (
      <Alert />
    );
  }

  // const getUserRole = () => {return role} ??? How can I call this in the roles prop in the provider?

  return (
    <ProfileProvider
      id={1}
      name={user?.name}
      roles={userRoles}
      setSelectedProfile={handleProfielChange}
      selectedProfileId={selectedProfileId}
    >
      ... App routes
    </ProfileProvider>
  );
};

The problem is that selectedProfileId is null initially and my app uses that null value in the provider for some reason then once it gets the data it gives the provider the proper value. I dont get it because if the profileLoading value is true then the Provider shouldnt render right?

Also, I need to have a function that sets the roles variable right now I have it static but I need to adjust the the user data I get from user Auth0 to get the userRole var. How can I do this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Have you tried doing something like so, it'll check to see if the profileLoading is false, then render ProfileProvider, otherwise you create some sort of loading screen or something before the render.

           {!profileLoading? 
            <> 
                <ProfileProvider
                    id={1}
                    name={user?.name}
                    roles={userRoles}
                    setSelectedProfile={handleProfielChange}
                    selectedProfileId={selectedProfileId}
                >
                ... App routes
                </ProfileProvider>
            </> : 
                <Loading /> 
            }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...