так вот мой аутентификатор. js код:
import locationHelperBuilder from 'redux-auth-wrapper/history4/locationHelper';
import { connectedRouterRedirect } from 'redux-auth-wrapper/history4/redirect';
import { createBrowserHistory } from 'history';
// import Spinner from '../components/layout/Spinner';
const locationHelper = locationHelperBuilder({});
createBrowserHistory();
export const UserIsAdmin = connectedRouterRedirect({
wrapperDisplayName: 'UserIsAdmin',
// AuthenticatingComponent: Spinner,
redirectPath: (state, ownProps) =>
locationHelper.getRedirectQueryParam(ownProps) || '/',
allowRedirectBack: true,
authenticatedSelector: state => state.user.isAuthenticated && state.user.isAdmin
});
export const UserIsAuthenticated = connectedRouterRedirect({
wrapperDisplayName: 'UserIsAuthenticated',
// AuthenticatingComponent: Spinner,
redirectPath: (state, ownProps) =>
locationHelper.getRedirectQueryParam(ownProps) || '/',
allowRedirectBack: true,
authenticatedSelector: state => state.user.isAuthenticated
});
export const UserIsNotAuthenticated = connectedRouterRedirect({
wrapperDisplayName: 'UserIsNotAuthenticated',
// AuthenticatingComponent: Spinner,
redirectPath: (state, ownProps) =>
locationHelper.getRedirectQueryParam(ownProps) || '/',
allowRedirectBack: true,
authenticatedSelector: state => !state.user.isAuthenticated
});
и вот где мне нужно сделать redux-auth-wrapper для ожидания, пока я не обновлю состояние с пользовательскими данными, чтобы отправить его где бы он ни находился до обновления страницы:
const MainRoutes = ( { cookies } ) => {
// state
const { isAuthenticated } = useSelector( state => state.user );
// dispatch
const dispatch = useDispatch();
const login = () => dispatch( loginAction() );
const logout = () => dispatch( logoutAction() );
// check if session is active ( cookie )
useEffect(() => {
if( !isAuthenticated ) {
const checkSession = async () => {
const cookie = cookies.get('token');
if( cookie && cookie.trim() !== '' ) {
axiosClient.defaults.headers.Authorization = `Bearer ${ cookie }`;
login();
} else logout();
};
checkSession()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ cookies, isAuthenticated ]);
return (
<Switch>
<Route exact path="/" component={ Courses } />
<Route path="/admin" component={ UserIsAdmin( Admin ) } />
<Route path="/profile" component={ UserIsAuthenticated( Profile ) } />
<Route exact path="/login" component={ UserIsNotAuthenticated( Login ) } />
<Route exact path="/signin" component={ UserIsNotAuthenticated( Signin ) } />
<Route exact path="/send-email" component={ UserIsNotAuthenticated( Email ) } />
<Route exact path="/recover" component={ UserIsNotAuthenticated( Recover ) } />
<Route exact path="/policy" component={ Policy } />
<Route exact path="/usage" component={ Usage } />
<Route exact path="/faqs" component={ FAQS } />
</Switch>
);
}
export default withRouter(withCookies(MainRoutes));
Здесь в основном я проверяю, существует ли сеансовый повар ie, поэтому я автоматически регистрирую пользователя. Проблема в том, что когда я go обращаюсь к некоторым route (например: / admin, который защищен и поэтому контролируется redux-auth.wrapper), и я повторно ссылаюсь на sh страницу, она всегда возвращает меня обратно в '/', потому что проверка isAuthenticated и isAdmin выполняется до того, как мой компонент MainRoutes может войти в систему пользователя, что, конечно, не проходит проверку в аутентифицированном селекторе auth. js и отправляет меня в '/'. Моя первая идея для решения этой проблемы состояла в том, чтобы сохранить эти 2 флага в localStorage, так что я перейду к предыдущему пути, даже если мой пользователь не завершил вход в систему. Но мне было интересно, есть ли какой-либо способ, в частности, сказать, чтобы приурочить -auth-wrapper, чтобы дождаться завершения моей функции useEffect.
Спасибо.