Skip to content

Commit

Permalink
Merge pull request #265 from Outblock:260-bug-async-issue-with-privat…
Browse files Browse the repository at this point in the history
…eroute

refactor: enhance PrivateRoute component with async wallet state checks
  • Loading branch information
tombeckenham authored Dec 9, 2024
2 parents 8d1d8ce + 4bed659 commit f3303e2
Showing 1 changed file with 35 additions and 14 deletions.
49 changes: 35 additions & 14 deletions src/ui/component/PrivateRoute.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,50 @@
import React, { useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import React, { useEffect, useState } from 'react';
import { Route, Redirect } from 'react-router-dom';

import { useWallet } from 'ui/utils';

const PrivateRoute = ({ children, ...rest }) => {
const wallet = useWallet();
const history = useHistory();
const [booted, setBooted] = useState(false);
const [unlocked, setUnlocked] = useState(false);
const [loading, setLoading] = useState(true);

// Everything through the wallet controller is async, so we need to check if the wallet is booted and unlocked in a useEffect
useEffect(() => {
let mounted = true;

const fetchLockState = async () => {
const booted = await wallet.isBooted();

if (!booted) {
return { booted, unlocked: false };
} else {
const unlocked = await wallet.isUnlocked();
return { booted, unlocked };
}
};

// useEffect(() => {
// getLockState()
// }, []);
fetchLockState().then(({ booted, unlocked }) => {
if (mounted) {
setBooted(booted);
setUnlocked(unlocked);
setLoading(false);
}
});

// const getLockState = async () => {
// const unlocked = await wallet.isUnlocked();
// if (!unlocked) {
// console.log('getLockState ==>', unlocked, children, rest.path);
// history.push('/unlock');
// }
// };
return () => {
mounted = false;
};
}, [wallet]);

return (
<Route
{...rest}
render={() => {
const to = !wallet.isBooted() ? '/welcome' : !wallet.isUnlocked() ? '/unlock' : null;
if (loading) {
return null;
}
const to = !booted ? '/welcome' : !unlocked ? '/unlock' : null;
return !to ? children : <Redirect to={to} />;
}}
/>
Expand Down

0 comments on commit f3303e2

Please sign in to comment.