How to make a structure in React that prevents an action from passing to another action before it is completed?

Viewed 47

When I make an api request, I save the returned data in redux store, then I use this data in the route.

What I want to do is to authorize the component before installing it on the route, but I cannot authorize as the data is undefined in the route. Especially when I refresh the page it becomes undefined.

so how do I prevent the currentUser from rendering the Route before it loads?

How should I solve this problem? Is there a tool to solve the problem?

componentDidMount

componentDidMount(){
    this.props.actions.getCurrentUser()
  }

Router <Redirect to = "/" /> redirects to this because currentUser was initially undefined

<Route exact path="/profile/:id/settings" render={(props) => {
            var urlId = props.match.params.id;
        return this.props.isLogged ? this.props.currentUser.id == urlId ? < ProfileSettings {...props} /> : <Redirect to={"/profile/" + urlId} /> : <Redirect to="/" />;
          }
   } />

react-redux

   function mapDispatchToProps(dispatch) {
      return {
        actions: {
          getCurrentUser: bindActionCreators(authAsyncActions.getCurrentUserApi, dispatch)
        }
      }
    }
  function mapStateToProps(state) {
      return {
        isLogged: state.isLoggedReducer,
        currentUser: state.currentUserReducer,
        isOwner: state.isOwnerReducer
      }
    }
 export default connect(mapStateToProps, mapDispatchToProps)(App);

getCurrentUserApi

export function getCurrentUserApi() {
    return async (dispatch, getState) => {
        if (localStorageHelper.isExistsToken()) {
            if (Object.keys(getState().currentUserReducer).length == 0) {
                await axios.get(CURRENT_USER_PATH, {
                    headers: localStorageHelper.authHeaderObj()
                }).then(res => {
                    dispatch(authActionsCreators.currentUserSuccess(res.data))
                    dispatch(authActionsCreators.isLoggedTSuccess())
                }).catch(err => {
                    if (err.response.status === 401) {
                        var refreshToken = bindActionCreators(refreshTokenApi, dispatch)
                        refreshToken();
                    }
                })
            }
        }
    }
}
0 Answers
Related