2

I'm trying to achieve a way to call the current user logged in info because I am going to make and if and else statement inside the AppJs to see if, he is a member he can see the user page if not he cannot or be redirected to the home page How I store my data:

  import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { loginUser } from '../../actions/authActions';
import classnames from 'classnames';
import { Button, Col, Form } from 'react-bootstrap';

class Login extends Component {
  constructor() {
    super();
    this.state = {
      storeUrl: '',
      errors: {},
    };
  }
  componentDidMount() {
    if (this.props.auth.isAuthenticated) {
      this.props.history.push('/backoffice');
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.auth.isAuthenticated) {
      this.props.history.push('/backoffice');
    }

    if (nextProps.errors) {
      this.setState({
        errors: nextProps.errors,
      });
    }
  }

  onChange = (e) => {
    this.setState({ [e.target.id]: e.target.value });
  };

  onSubmit = (e) => {
    e.preventDefault();

    const userData = {
      storeUrl: this.state.storeUrl,
    };
    this.props.loginUser(userData);
  };
  render() {
    const { storeUrl, errors } = this.state;
    return (
      <>
        <div className='container-fluid'>
          <div className='row no-gutter'>
            <div className='d-none d-md-flex align-items-center col-md-4 col-lg-6 bg-image'>
              <div className='vd-hero vd-hero--transparent'>
                <img
                  src={require('../../img/logo.svg')}
                  alt=''
                  className='logo mx-auto'
                />
                <h1 className='vd-hero-headline'>
                  Join 25,000+ retailers already growing their business with
                  PosHub
                </h1>
              </div>
              <img
                src={require('../../img/signup-bag.svg')}
                srcSet={require('../../img/signup-bag.svg')}
                sizes='(max-width: 1400px) 1000px,
                    2000px'
                className='signup-bag'
                alt=''
              />
              <div className='curve'></div>
            </div>
            <div className='col-md-8 col-lg-6'>
              <div className='d-flex justify-content-between'>
                <div className='backHome'>
                  <i className='primaryBlue fa fa-arrow-circle-left'></i>{' '}
                  <Link to='/' className='underline'>
                    Back to Home
                  </Link>
                </div>
                <div className='sign-in'>
                  Not registered?{' '}
                  <Link to='/register' className='underline'>
                    Sign up now
                  </Link>
                </div>
              </div>
              <div className='login d-flex align-items-center pb-5'>
                <div className='container'>
                  <div className='row'>
                    <div className='col-10 mx-auto'>
                      <div className='vd-hero vd-hero--transparent'>
                        <h1 className='vd-hero-headline h1-customize'>
                          Log in to your account
                        </h1>
                      </div>
                      <Form onSubmit={this.onSubmit}>
                        <Form.Row>
                          <Form.Group as={Col}>
                            <Form.Label>Store URL</Form.Label>
                            <div className='suffix'>
                              <Form.Control
                                type='url'
                                id='storeUrl'
                                placeholder='Enter storeUrl'
                                value={storeUrl}
                                error={errors.storeUrl}
                                autoComplete='something-unsupported'
                                onChange={this.onChange}
                                className={classnames('form-control', {
                                  invalid: errors.storeUrl,
                                })}
                              />
                              <span className='red-text'>
                                {errors.storeUrl}
                                {errors.storeUrlnotfound}
                              </span>
                            </div>
                          </Form.Group>
                        </Form.Row>
                        <Button
                          className='btn btn-primary btn-block btn-lg'
                          variant='primary'
                          type='submit'
                        >
                          Log In
                        </Button>
                      </Form>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </>
    );
  }
}

Login.propTypes = {
  loginUser: PropTypes.func.isRequired,
  auth: PropTypes.object.isRequired,
  errors: PropTypes.object.isRequired,
};

const mapStateToProps = (state) => ({
  auth: state.auth,
  errors: state.errors,
});

export default connect(mapStateToProps, { loginUser })(Login);

App.js

import React from 'react';
import Home from './components/layout/Home';
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Redirect,
} from 'react-router-dom';
import User from './components/layout/users/User';
import AddUser from './components/layout/users/AddUser';
import EditUser from './components/layout/users/EditUser';
import { Provider } from 'react-redux';
import store from './store';
import jwt_decode from 'jwt-decode';
import setAuthToken from './util/setAuthToken';
import { setCurrentUser, logoutUser } from './actions/authActions';

if (localStorage.jwtToken) {
  const token = localStorage.jwtToken;
  setAuthToken(token);
  const decoded = jwt_decode(token);
  store.dispatch(setCurrentUser(decoded));
  const currentTime = Date.now() / 1000;
  if (decoded.exp < currentTime) {
    store.dispatch(logoutUser());
    window.location.href = './login';
  }
}
 const {user } = this.users


function App() {

  return (

    <Provider store={store}>
      <Router>
        <div className='App'>
          {/* <NavBar /> */}
          <Route path='/forget/password' component={ForgotPassword} exact />

          <Switch>
            <Route path='/' component={HomePage} exact />
            <Route path='/register' component={Register} exact />
            <Route path='/login' component={Login} exact />
            <Route path='/backoffice' component={Home} exact />
            {/* Transaction */}
            <PrivateRoute path='/transactions' component={Transactions} exact />
            <PrivateRoute
              path='/transactions/new'
              component={AddTransactions}
              exact
            />
            <PrivateRoute
              path='/transactions/edit/:id'
              component={EditTransactions}
              exact
            />
            <PrivateRoute
              path='/transactions/returns'
              component={Returns}
              exact
            />
            <PrivateRoute
              path='/transactions/returns/new'
              component={AddReturns}
              exact
            />
            <PrivateRoute
              path='/transactions/returns/edit/:id'
              component={EditReturns}
              exact
            />
            <PrivateRoute
              path='/transactions/preorders'
              component={PreOrders}
              exact
            />
            <PrivateRoute
              path='/transactions/preorders/new'
              component={AddPreOrders}
              exact
            />
            <PrivateRoute
              path='/transactions/preorders/edit/:id'
              component={EditPreOrders}
              exact
            />

            {/* Loyalty */}
            <PrivateRoute
              path='/loyalty/cashbackQuota'
              component={CashBack}
              exact
            />
            <PrivateRoute
              path='/loyalty/settings'
              component={LSettings}
              exact
            />

            {/* Projects */}
            <PrivateRoute path='/products' component={Products} exact />
            <PrivateRoute path='/products/new' component={AddProducts} exact />
            <PrivateRoute
              path='/products/edit/:id'
              component={EditProducts}
              exact
            />
            <PrivateRoute
              path='/products/pricebooks'
              component={PriceBooks}
              exact
            />
            <PrivateRoute
              path='/products/pricebooks/new'
              component={AddPriceBooks}
              exact
            />
            <PrivateRoute
              path='/products/pricebooks/edit/:id'
              component={EditPriceBooks}
              exact
            />
            {/* onlinonlineStore */}
            <PrivateRoute
              path='/onlineStore/gettingStarted'
              component={GettingStarted}
              exact
            />
            <PrivateRoute
              path='/onlineStore/orders'
              component={OnlineOrders}
              exact
            />
            <PrivateRoute
              path='/onlineStore/orders/new'
              component={AddOrders}
              exact
            />
            <PrivateRoute
              path='/onlineStore/orders/edit/:id'
              component={EditOrders}
              exact
            />
            <PrivateRoute
              path='/onlineStore/appearance'
              component={Appearance}
              exact
            />
            <PrivateRoute
              path='/onlineStore/setup'
              component={OnlineStoreSetup}
              exact
            />
            <PrivateRoute
              path='/onlineStore/marketing'
              component={OnlineMarketing}
              exact
            />

            <PrivateRoute
              path='/onlineStore/payouts'
              component={OnlinePayouts}
              exact
            />
            <PrivateRoute path='/qrordering' component={QROrder} exact />
            {/* Send SMS */}
            <PrivateRoute
              path='/products/suppliers'
              component={Suppliers}
              exact
            />
            <PrivateRoute
              path='/products/suppliers/new'
              component={AddSupplier}
              exact
            />
            <PrivateRoute
              path='/products/suppliers/edit/:id'
              component={EditSupplier}
              exact
            />
            {/* Stocks */}
            <PrivateRoute
              path='/stocks/supplyNeeds'
              component={SupplyNeeds}
              exact
            />
            <PrivateRoute
              path='/stocks/supplyNeeds/new'
              component={AddSupplyNeeds}
              exact
            />
            <PrivateRoute
              path='/stocks/supplyNeeds/edit/:id'
              component={EditSupplyNeeds}
              exact
            />
            <PrivateRoute
              path='/stocks/purchaseOrders'
              component={PurchaseOrders}
              exact
            />
            <PrivateRoute
              path='/stocks/purchaseOrders/new'
              component={AddPurchaseOrders}
              exact
            />
            <PrivateRoute
              path='/stocks/purchaseOrders/edit/:id'
              component={EditPurchaseOrders}
              exact
            />
            <PrivateRoute
              path='/stocks/stockReturn'
              component={StockReturn}
              exact
            />
            <PrivateRoute
              path='/stocks/stockReturn/new'
              component={AddStockReturn}
              exact
            />
            <PrivateRoute
              path='/stocks/stockReturn/edit/:id'
              component={EditStockReturn}
              exact
            />
            <PrivateRoute
              path='/stocks/stocktakes'
              component={StockTakes}
              exact
            />
            <PrivateRoute
              path='/stocks/stockTransfers'
              component={StockTransfers}
              exact
            />
            <PrivateRoute
              path='/stocks/stockTransfers/new'
              component={AddStockTransfer}
              exact
            />
            <PrivateRoute
              path='/stocks/stockTransfers/edit/:id'
              component={EditStockTransfer}
              exact
            />
            <PrivateRoute
              path='/stocks/auditTrail'
              component={AuditTrail}
              exact
            />
            <PrivateRoute path='/promotions' component={Promotions} exact />
            <PrivateRoute
              path='/promotions/new'
              component={AddPromotions}
              exact
            />
            <PrivateRoute
              path='/promotions/edit/:id'
              component={EditPromotions}
              exact
            />
            <PrivateRoute path='/promotions/cfds' component={Cfds} exact />
            <PrivateRoute path='/customers' component={Customers} exact />
            <PrivateRoute
              path='/customers/new'
              component={AddCustomers}
              exact
            />
            <PrivateRoute
              path='/customers/edit/:id'
              component={EditCustomers}
              exact
            />
            {/* Report */}
            <PrivateRoute
              path='/reports/sales/over-time'
              component={OverTime}
              exact
            />
            <PrivateRoute
              path='/reports/sales/product'
              component={ProductSales}
              exact
            />
            <PrivateRoute
              path='/reports/sales/category'
              component={Category}
              exact
            />
            <PrivateRoute
              path='/reports/sales/variant'
              component={Variant}
              exact
            />
            <PrivateRoute path='/reports/sales/sku' component={Sku} exact />
            {/* Profile */}
            {/* <PrivateRoute
              path='/reports/sales/employee'
              component={Profile}
              exact
            /> */}
            <PrivateRoute
              path='/reports/sales/employee'
              component={SaleEmployee}
              exact
            />
            <PrivateRoute
              path='/reports/sales/transaction-channel'
              component={TransactionC}
              exact
            />
            <PrivateRoute
              path='/reports/sales/payment-method'
              component={PaymentMethod}
              exact
            />
            <PrivateRoute
              path='/reports/sales/shifts'
              component={Shifts}
              exact
            />
            <PrivateRoute
              path='/reports/loyalty'
              component={ReportLoyal}
              exact
            />
            <PrivateRoute
              path='/reports/products/stockValue'
              component={StockValue}
              exact
            />
            <PrivateRoute
              path='/reports/products/pre-order'
              component={PreOrdersReport}
              exact
            />
            <PrivateRoute
              path='/reports/promotions'
              component={ReportPromotions}
              exact
            />
            <PrivateRoute path='/reports/bir/pos' component={POSReport} exact />
            <PrivateRoute
              path='/reports/bir/zreadings'
              component={ZReadReport}
              exact
            />
            <PrivateRoute path='/employees' component={Employees} exact />
            <PrivateRoute path='/employees/new' component={AddEmployee} exact />
            <PrivateRoute
              path='/employees/edit/:id'
              component={EditEmployee}
              exact
            />

            <PrivateRoute
              path='/employees/timesheets'
              component={Timesheets}
              exact
            />
            <PrivateRoute
              path='/employees/performance'
              component={EmployeePerformance}
              exact
            />
            <PrivateRoute
              path='/employees/activityLog'
              component={ActivityLog}
              exact
            />
            <PrivateRoute path='/settings/account' component={Accounts} exact />
            <PrivateRoute path='/settings/tax' component={Tax} exact />
            <PrivateRoute
              path='/settings/paymentOptions'
              component={PaymentOptions}
              exact
            />
            <PrivateRoute
              path='/settings/billing/plans'
              component={BillingPlans}
              exact
            />
            <PrivateRoute
              path='/settings/billing/sms'
              component={SmsPOS}
              exact
            />
            <PrivateRoute
              path='/settings/stores'
              component={SettingsStore}
              exact
            />
            <PrivateRoute
              path='/settings/stores/new'
              component={AddSettingsStore}
              exact
            />
            <PrivateRoute
              path='/settings/stores/edit/:id'
              component={EditSettingsStore}
              exact
            />
            <PrivateRoute
              path='/settings/bank-accounts'
              component={BankAccounts}
              exact
            />
            <PrivateRoute
              path='/settings/bank-accounts/new'
              component={AddBankAccounts}
              exact
            />
            <PrivateRoute
              path='/settings/bank-accounts/edit/:id'
              component={EditBankAccounts}
              exact
            />
            <PrivateRoute
              path='/settings/receipts'
              component={Receipts}
              exact
            />
            <PrivateRoute
              path='/settings/receipts/new'
              component={AddReceipts}
              exact
            />
            <PrivateRoute
              path='/settings/receipts/edit/:id'
              component={EditReceipts}
              exact
            />
            <PrivateRoute
              path='/settings/registers'
              component={Registers}
              exact
            />
            <PrivateRoute
              path='/settings/ipad-layouts'
              component={IpadLayouts}
              exact
            />
            <PrivateRoute path='/settings/addOns' component={AddOns} exact />
            <PrivateRoute path='/support/help' component={Help} exact />
            <PrivateRoute
              path='/support/featureRequest'
              component={FeatureRequest}
              exact
            />

{user.status === 'Member' ? (
    <>
      <PrivateRoute path="/admin/users" component={User} exact />
      <PrivateRoute path="/admin/users/create" component={AddUser} exact />
      <PrivateRoute path="/admin/users/edit/:id" component={EditUser} exact />
    </>
  ) : (
    <Redirect to="/backoffice" />
  )}
        

            {/* HomePage */}
            <Route path='/pricing' component={PricingPlans} exact />
            <Route path='/multi-store' component={MultiStore} exact />
            <Route path='/why-choose-poshub' component={WhyPosHub} exact />
            {/* Navbar Right */}
            <Route path='/contact-sales' component={ContactSales} exact />
            <Route path='/get-selling' component={GetSelling} exact />
            <Route path='/examples' component={BusinessTypes} exact />
            <Route
              path='/examples/sports-and-outdoors-pos'
              component={SportsOutdoors}
              exact
            />
            <Route
              path='/examples/homeware-and-gift-shop-pos'
              component={HomewareStores}
              exact
            />
            <Route
              path='/examples/fashion-boutique-pos'
              component={FashionBoutique}
              exact
            />
            <Route path='/grow-more' component={GrowMore} exact />
            <Route path='/add-the-smarts' component={AddSmarts} exact />
            <Route path='/tour' component={FeatureOverview} exact />
            <Route path='/tour/point-of-sale' component={PointOfSale} exact />
            <Route path='/enterprise' component={Enterprise} exact />
            <Route path='/get-started' component={GetStarted} exact />
            <Route path='/retail-resource-hub' component={AllResources} exact />
            <Route
              path='/tour/pos-reporting'
              component={ReportingInsights}
              exact
            />
            <Route path='/tour/hardware-solutions' component={Hardware} exact />
            <Route
              path='/tour/inventory-management-software'
              component={InventoryManagement}
              exact
            />
            <Route
              path='/tour/customer-management-software'
              component={CustomerManagement}
              exact
            />
            <Route path='/tour/pos-support' component={AwardSupport} exact />
            <Route
              path='/tour/ecommerce-solutions'
              component={EcommerceSolutions}
              exact
            />
            <Route
              path='/customers-case-studies'
              component={CaseStudies}
              exact
            />
            <Route
              path='/tour/accept-payments'
              component={AcceptPayments}
              exact
            />
            <Route path='/security' component={Security} exact />
            <Route
              path='/tour/pos-integrations-add-ons'
              component={HomeAddOns}
              exact
            />
            <Route path='/scanner' component={HomeScanner} exact />

          </Switch>

        </div>
      </Router>
    </Provider>
  );
}



export default App;

But the problem is that it says the user is not defined so how to make a const and call it. Thanks for your help

15
  • This is not the part where I can see user object. Can you add more code for the first render return? So the whole component Commented Dec 25, 2020 at 12:03
  • I dont get what you are trying to say do u have teamviewer so you could check Im so sorry Commented Dec 25, 2020 at 12:06
  • So, add your whole component code for this part of code user.status === 'Member'. This is the first part of your question Commented Dec 25, 2020 at 12:08
  • so basically I will give you the code of the user component?? Commented Dec 25, 2020 at 12:11
  • Yes. You can put it here or make codesandbox Commented Dec 25, 2020 at 12:11

3 Answers 3

1

user object is probably undefined at the beginning.

You should add initial check before you try to access .status:

if(!user) {
  return null
};

return {
  user.status === 'Member' ? (
    <>
      <PrivateRoute path="/admin/users" component={User} exact />
      <PrivateRoute path="/admin/users/create" component={AddUser} exact />
      <PrivateRoute path="/admin/users/edit/:id" component={EditUser} exact />
    </>
  ) : (
    <Redirect to="/backoffice" />
  )
}
Sign up to request clarification or add additional context in comments.

8 Comments

hello how do u call the current user logged in the page??
Can you share the rest of your code. Edit your question and add more code so i can provide you with answers
what do u wanted to see in my code that will help you solve my problem??
How do you store data in your application? That part of code. Do you store it state, store?
here is this what you wanted to see??
|
0

Create a custom router

const UserMemberRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props => ((user || {}).status === 'Member' ? (
      <Component {...props} />
    ) : (
      <Redirect to={{
        pathname: '/backoffice',
        state: {
          from: props.location
        }
      }}
      />
    )
    )}
  />
);

and use this route wherever you needed like

<UserMemberRoute path="/admin/users" component={User} exact />
<UserMemberRoute path="/admin/users/create" component={AddUser} exact />
<UserMemberRoute path="/admin/users/edit/:id" component={EditUser} exact />

this is the efficient way to achieve custom routes.

Comments

0

There is possibility pass props in router - it can be done like this:

<Route path={routes.myProfile} component={() => <MyProfile user ={user}/>} />

Next in the MyProfile component, you have currentUser access like props.

Also it's valuable to consider that currentUser information are using a lot times across differeent component, so it can be stored in global access like:

  • local storage
  • context
  • redux

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.