在页面呈现之前使用fetch设置状态



我正在为React组件构建一个守卫。守卫接受一个Auth0 JWT并检查我们的API以查看该用户是否存在于我们的数据库中。如果用户确实存在,我们将userExists设置为true,并将其重定向到/dashboard。如果用户不存在,我们调用postUser并将它们发送给/complete-profile

我遇到的问题是,在userExists正确被fetch调用设置之前,页面正在渲染。换句话说,如果我要运行下面的代码,日志将按照以下顺序读取:

  1. 用户不存在
  2. fetch call 1

const SomeGuard: FC<SomeGuardProps> = ({ children }) => {
const { isAuthenticated } = useAuth();
const isMountedRef = useIsMountedRef();
const [userExists, setUserExists] = React.useState(true);
const getUser = useCallback( async () => {
try {
var user_exists;
fetch(`https://website.com/user`,
{
headers: {
Authorization: `Bearer DFJKS54DUJ6DD.SDF2KJWEF4NKN3JKw4534.DFSKJ5HSKDJ6HF`,
},
method: 'GET',
},
).then(response => {
if (response.status===200) { // USER EXISTS
console.log("FETCH CALLED 1")
setUserExists(true);
}
else if (response.status===404) { // catch 404 -- USER NOT FOUND
console.log("FETCH CALLED 2")
setUserExists(false);
}

return response.json();
})
}
catch (e) {
console.error(e);
}
}, [isMountedRef]);

const postUser = useCallback( async () => {
// assume this works and sends a POST request to our API
// to create a user
)}

useEffect(() => {
console.log("STEP 1");
getUser();
}, [getUser]);

if (isAuthenticated) {
if (!userExists) {
console.log("USER DOES NOT EXIST");
postUser();
return <Redirect to="/complete-profile" />;
}
else if (userExists) {
console.log("USER DOES EXIST");
return <Redirect to="/dashboard" />;
}
}
if (!isAuthenticated) {
console.log("TRIED TO HIT DASHBOARD WITHOUT BEING LOGGED IN");
return <Redirect to="/login" />;
}
return (
<>
{children}
</>
);
};

SomeGuard.propTypes = {
children: PropTypes.node
};
export default SomeGuard;

因为它在调用fetch之前呈现页面,所以我最初设置的userExists的值总是决定呈现哪个页面。

请帮忙!我遗漏了什么?在渲染页面之前,我如何获得fetch调用来更新userExists?

userExists的初始值设置为其他值,例如null,这样您就可以将未加载的页面与已加载的页面以及true/loaded和false页面区分开来。然后,只有在userExists不为空时才渲染子元素:

const [userExists, setUserExists] = React.useState(null);
if (isAuthenticated) {
if (userExists === false) {
console.log("USER DOES NOT EXIST");
postUser();
return <Redirect to="/complete-profile" />;
}
else if (userExists === true) {
console.log("USER DOES EXIST");
return <Redirect to="/dashboard" />;
}
}
return userExists === null ? null : children;

相关内容

  • 没有找到相关文章

最新更新