0

I am having some issues in displaying a separate component based on the type of user.

Detailed Explanation of what I am trying to achieve:

The code snippet where I am having issues is as follows:

const addDataRequest = this.state.addDataRequestVisible ? (
            <div className="main-page-section">
               
                <Growl ref={this.growl}/>
                {isAdmin(user)? (
                
                <AdminDataRequestEnhancedForm handleSubmit={this.handleSubmit} addProject={this.addProjectOpen} onCancel={this.handleCancel}/>
               
                ) : (
               <DataRequestEnhancedForm handleSubmit={this.handleSubmit} addProject={this.addProjectOpen} onCancel={this.handleCancel}/>
                )
              }
            </div>
        ) : null;
    

Right now, DataRequestFormJS andAdminDataRequestForm are exact same forms as far as form content is concerned. So based on the user role, if it's an Admin, I want to display AdminDataRequestEnhancedForm component and if it's not an Admin, I want to display DataRequestEnhancedForm component. But even though, I have specific checks for isAdmin in place, as shown in the code snippet above, it's not displaying AdminDataRequestEnhancedForm component for an Admin user. I am wondering what's wrong I am doing? Does it have something to do with the state variable -this.state.addDataRequestVisible?

Here is the complete code:

import {DataRequestEnhancedForm} from "./DataRequestFormJS";
import {AdminDataRequestEnhancedForm} from "./AdminDataRequestForm";
import {isAdmin} from './auth';

class DataRequest extends React.Component<any, any> {
    private growl = React.createRef<Growl>();

    constructor(props) {
        super(props);
       
        this.state = {
            result: '',
            addDataRequestVisible: false,
            addProjectVisible: false,
            //For admin specific
            addAdminDataRequestVisible: false,
            addAdminProjectVisible: false
        };

        this.handleSubmit = this.handleSubmit.bind(this)
        this.handleCancel = this.handleCancel.bind(this)
        this.addProjectOpen = this.addProjectOpen.bind(this)
        this.addProjectClose = this.addProjectClose.bind(this)
    }

    handleSubmit = (values) => {

       let responseData = []
        axios.post('upms/saveData', {
            
        }).then((response) => {
            console.log('response', response)
            responseData = response.data

            this.setState({
                addDataRequestVisible: false,
                dataRequestFormVisible: false,
                dataRequestGridVisible: true,
                selectedDataRequest: []
            }, () => {
                this.growl.current.show({
                    severity: 'success',
                    summary: 'Save Successful',
                    detail: 'Data Request has been created'
                })
            })
        }).catch((err) => {
            this.growl.current.show({
                severity: 'error',
                summary: 'Save Unsuccessful',
                detail: 'Could not add Data Request'
            })
        })
    }

    handleCancel = event => {
        console.log('In handleCancel....')
        if (event) {
            this.setState({ addDataRequestVisible: false})
        }
    }

    addProjectOpen = event =>{
        if (event) {
            this.setState({ addProjectVisible: true})
        }
    }

    addProjectClose = event =>{
        console.log('In addProjectClose....' + event)
        if (event) {
            this.setState({ addProjectVisible: false})
        }
    }

    render() {
        const user = JSON.parse(sessionStorage.getItem('loggedInUser'))
        let url = isAdmin(user) ? 'url1' : 'api/personnels/' + user.id + '/url2'

        const defaultView = this.state.addDataRequestVisible?null: (
            <div className="data-request-main-section">
                <Growl ref={this.growl}/>
                <div className="page-title-section">            
                <Button label="New Data Request" icon="pi pi-plus" className="new-data-req-btn"
                        onClick={(e) => this.setState({ addDataRequestVisible: true})}/>
            </div>
                <DataRequestsDataTable url={url} handleSubmit={this.handleSubmit}/>
            </div>

        )

       
         
        

        const addDataRequest = this.state.addDataRequestVisible ? (
            <div className="main-page-section">
               
                <Growl ref={this.growl}/>
                {isAdmin(user)? (
                
                <AdminDataRequestEnhancedForm handleSubmit={this.handleSubmit} addProject={this.addProjectOpen} onCancel={this.handleCancel}/>
               
                ) : (
               <DataRequestEnhancedForm handleSubmit={this.handleSubmit} addProject={this.addProjectOpen} onCancel={this.handleCancel}/>
                )
              }
            </div>
        ) : null;
       


        const addProjectDialog = this.state.addProjectVisible ? (
            <Dialog visible={true} modal={true} className="add-project-popup"
                    onHide={() => this.setState({addProjectVisible: false})}>
                <div style={{textAlign: 'center'}}>
                    <h3>Add New Project</h3>
                    <AddNewProjectForm closeProject={this.addProjectClose} />
                </div>
            </Dialog>
        ) : null

        return (
            <div className="datareq-page">
                {defaultView}
                {addDataRequest}
                {addProjectDialog}
            </div>
        );
    }
}

export default DataRequest

My auth.js looks like following:

export const isAdmin = (user) => {
    return JSON.parse(sessionStorage.assignees).some(assignee => assignee.id === user.id)
}
Tan
  • 1,433
  • 5
  • 27
  • 47
  • Did you try consoling what your function returns? Maybe it' not returning what you expected it to return. To be sure about that do : `console.log(isAdmin(user))` and see what you're getting. – Blessing Apr 07 '21 at 15:41
  • Yes. It is returning true. – Tan Apr 07 '21 at 15:45
  • You said that it's not returning `AdminDataRequestEnhancedForm`, then what is it returning @Tan ? – Blessing Apr 07 '21 at 15:56
  • @Blessing It's taking me to `DataRequestEnhancedForm` component. When I made some changes in `AdminDataRequestEnhancedForm`, it's not showing the changes even though `isAdmin(user)` is true. – Tan Apr 07 '21 at 16:03
  • It seems like your function `isAdmin` is `asynchronous` and doesn't return the result directly and by the time it finishes executing `DataRequestEnhancedForm` will have been rendered instead. Try making that `isAdmin` function asynchronous. – Blessing Apr 07 '21 at 16:06
  • @Blessing I edited my post to include `isAdmin` function. Please take a look. Are you saying that I should make some changes in there? – Tan Apr 07 '21 at 16:15
  • Consider checking my answer below @Tan . – Blessing Apr 07 '21 at 16:24

1 Answers1

1

It seems like your function isAdmin doesn't return the result directly and by the time it finishes executing DataRequestEnhancedForm will have been rendered instead. Try making that isAdmin function asynchronous like this:

export const isAdmin = async (user) => {

    let userType = await JSON.parse(sessionStorage.assignees).some(assignee => assignee.id === user.id)
 
    return userType

}
Blessing
  • 2,450
  • 15
  • 22
  • After making this change, I am getting `Uncaught ReferenceError: regeneratorRuntime is not defined` error. – Tan Apr 07 '21 at 16:37
  • It's a problem of your `babel` configurations. Check this https://stackoverflow.com/questions/33527653/babel-6-regeneratorruntime-is-not-defined – Blessing Apr 07 '21 at 16:44
  • Would mind giving the answer an upvote too? That would be helpful. Cheers! – Blessing Apr 09 '21 at 21:47