Skip to content
Advertisement

handling undefined in handleSubmit function

I am running into an issue in my React app with the handleSubmit function as explained below.

Brief overview:

In order to handle employeeSets and projects for the axios put, I have to put certain arrays related checks as shown below. In a scenario when both employee and project are an array, my control reaches the first if block where I have the console.log saying –

INSIDE if block since both employeeSets and projects are an array.

I am noticing that sometimes, values.employeeSets[0].employeeSetId is undefined and hence handleSubmit doesn’t work. Basically, it doesn’t let users to submit anything. How can I fix it? I would probably want to pass a null value if it’s undefined.

Also, can there be any improvement in the array related checks that I have made in the code?

handleSubmit = (values) => {
    console.log("Array testing for employeeSets and Protocols");
    console.log("Is Employee an array?");
    console.log(Array.isArray(values.employeeSets));
    console.log("Is Project an array?");
    console.log(Array.isArray(values.protocols));
    if (values.requestId && values.requestId > 0) {
        if(Array.isArray(values.employeeSets) && Array.isArray(values.projects)){
            console.log("INSIDE if block since both employeeSets and projects are an array");
            axios.put(`upms/saveData`, {
                requestId: values.requestId,
                projectId: values.projectId,
                employeeSets: deriveEmployeeArray(values.employeeSets[0].employeeSetId),
                projects: deriveProjectArray(values.projects[0].projectId),
            }).then((response) => {
                console.log('response', response)
                this.setState({
                    dataRequestFormVisible: false,
                    dataRequestGridVisible: true,
                    dataRequestFormSection: true,
                    selectedDataRequest: []
                }, () => {
                    this.growl.show({severity: 'success', summary: 'Save Successful', detail: 'Data Request Saved'})
                })
                this.fetchRecords()
            }).catch((err) => console.log(err));
        } else if(!Array.isArray(values.employeeSets) && Array.isArray(values.projects)){ 
            console.log("projects => ARRAY and EmployeeSet => Not and array")
            axios.put(`upms/saveData`, {
                requestId: values.requestId,
                projectId: values.projectId,
                employeeSets: deriveEmployeeArray(values.employeeSets),
                projects: deriveProjectArray(values.projects[0].projectId),
            }).then((response) => {
                console.log('response', response)
                this.setState({
                    dataRequestFormVisible: false,
                    dataRequestGridVisible: true,
                    dataRequestFormSection: true,
                    selectedDataRequest: []
                }, () => {
                    this.growl.show({severity: 'success', summary: 'Save Successful', detail: 'Data Request Saved'})
                })
                this.fetchRecords()
            }).catch((err) => console.log(err));
        }//End of else if
        else if(Array.isArray(values.employeeSets) && !Array.isArray(values.projects)){ 
            console.log("EmployeeSets => ARRAY and projects => Not and array")
            axios.put(`upms/saveData`, {
                requestId: values.requestId,
                projectId: values.projectId,
                employeeSets: deriveEmployeeArray(values.employeeSets[0].employeeSetId),
                projects: deriveProjectArray(values.projects),
            }).then((response) => {
                console.log('response', response)
                this.setState({
                    dataRequestFormVisible: false,
                    dataRequestGridVisible: true,
                    dataRequestFormSection: true,
                    selectedDataRequest: []
                }, () => {
                    this.growl.show({severity: 'success', summary: 'Save Successful', detail: 'Data Request Saved'})
                })
                this.fetchRecords()
            }).catch((err) => console.log(err));
        }// End of else if
        else{
            console.log("INSIDE ELSE block since both are not an array");
            axios.put(`upms/saveData`, {
                requestId: values.requestId,
                projectId: values.projectId,
                employeeSets: deriveEmployeeArray(values.employeeSets),
                projects: deriveProjectArray(values.projects),    
            }).then((response) => {
                console.log('response', response)
                this.setState({
                    dataRequestFormVisible: false,
                    dataRequestGridVisible: true,
                    dataRequestFormSection: true,
                    selectedDataRequest: []
                }, () => {
                    this.growl.show({severity: 'success', summary: 'Save Successful', detail: 'Data Request Saved'})
                })
                this.fetchRecords()
            }).catch((err) => console.log(err));
        }
        // End of else
   }
}

function deriveEmployeeArray(employee) {
    if(employee.length == 0){
        return ""
    }
    else{
        return [employee] ;
    }
}

function deriveProjectArray(project) {
    if(project.length == 0){
        return ""
    }else
    {
        return [project];
    }
}

Advertisement

Answer

Looking at your post parameters.

requestId: values.requestId,
projectId: values.projectId,
employeeSets: deriveEmployeeArray(values.employeeSets[0].employeeSetId),
projects: deriveProjectArray(values.projects[0].projectId),

There are 3 recommendations.

1 Don’t use array, use plain object. e.g.

value = { requestId: 123, projectId: 123. employeeSets: 1234, projects: 'some project' }

2 If you really need to use array, then just check the ID directly.

if (values.employeeSets[0].employeeSetId) {
   ... do something
} 

3 If you want to return either the array or alternatively null, you can also do something like this.

requestId: values.requestId,
projectId: values.projectId,
employeeSets: deriveEmployeeArray(values.employeeSets[0]?.employeeSetId) || null,
projects: deriveProjectArray(values.projects[0]?.projectId) || null,

Ideally, all these If-Else statements should not be necessary in onSubmit function, and should be checked/defined within deriveEmployeeArray and deriveProjectArray (cleaner codes).

function deriveEmployeeArray(employee) {
  
    return Array.isArray(employee) ? employee :  ''
     // if not array, then just return empty string.
     // If employee could be a string OR an array OR empty, u can also do 
     // return employee || ''
}
Advertisement