Test for null value in the code at the time of submitting a form

What I am trying to achieve:

I am trying to pass the value of fileId as N if sessionStorage.getItem('uploadedFiles') is null. However, if the value exists, I want to pass the existing value from the session storage.

Scenario 1:

User may submit a form without uploading the file. In this case, the value of sessionStorage.getItem('uploadedFiles') is going to be null.

Scenario 2 :

User uploads a file using the Attach Files button. So inside fileUpload function, I am storing the value of fileId in session storage using the following code:

 growlComp.show({severity: 'success', summary: 'File Upload successful', detail: 'File Upload was successful'})
 sessionStorage.setItem('uploadedFiles', JSON.stringify(fileArray))      

Problem:

Inside mapPropsToValues: props => {, as shown in the code below,I have tried to put a check using var fileIdValue = sessionStorage.getItem('uploadedFiles') ;
but this always prints null when a submit button is clicked, regardless of someone uploading the file or not.

How can I test for the null inside this line of code for the fileId variable and if it is null, I want to send fileId: ['N'], and if it is not null, then I want to send the value from the session storage?

I was thinking of using ternary expression but that doesn’t fit with if statement.

  return {
            createDate: props.testRequest && props.testRequest.createDate || '',
            startDate: props.testRequest && props.testRequest.startDate || '',
            completeDate: props.testRequest && props.testRequest.completeDate || '',
            edwEmployeeId: props.testRequest && props.testRequest.employeeId || '',
            fileId: [sessionStorage.getItem('uploadedFiles')], 
				  
        }

Here is my code (many things are removed for brevity purpose)

import React from 'react';
import {Field, Form, useField, withFormik} from 'formik';
import {Button, InputLabel,Menu,MenuItem, Select, TextField, TextareaAutosize} from '@material-ui/core'
import * as Yup from 'yup'
import {AutoCompanys} from './forms/AutoCompanys';
//more imports here


const CompanyRequestFormAbc = (props) => {

    const {values, setFieldValue, touched, errors, isSubmitting, handleReset, handleChange} = props;
  

    const fileUpload = (e) => {
        console.log('fileupload triggered....' + e.files)
		const growlComp = growl.current
		
		 let formData = new FormData();
			e.files.forEach((file, i) => formData.append(`files`, file))
		
		 axios.post('abc/userFileUpload?//some parameters, formData,{
            headers: {
                "Content-Type": "multipart/form-data"
            }
        }).then((response) => {
            var filedata = response.data;
            filedata = filedata.filter(v=>v!='');

            var fileArray = [];
            filedata.forEach(element => {
                if(element.indexOf(",")){
                    var splitString = element.split(",");
                    fileArray.push(splitString[0]);
                }
            });

            growlComp.show({severity: 'success', summary: 'File Upload successful', detail: 'File Upload was successful'})
            sessionStorage.setItem('uploadedFiles', JSON.stringify(fileArray))
           
        }).catch((response) => {
            growlComp.show({severity: 'error', summary: 'File Upload unsuccessful', detail: 'File Upload was unsuccessful'})
            console.log('Could not upload files.....')
        })

        


       
    }

    return (
        <div>
           <div id="formDiv">

                <Form className="form-column-3">

                    <div className="form-field">
                        <FileUpload
                            name="files"
                            mode='advanced'
                            uploadHandler={fileUpload}
                            customUpload={true}
                            chooseLabel="Attach Files"
                            multiple={false}/>
                    </div> 
                    
                                        
                    </div> 
                    <div className="btn-group-right">
                        <Button size="large" variant="contained" color="primary"
                                type="submit">Submit</Button>
                        <Button size="large" variant="contained" color="primary" onClick={handleReset}
                                style={{marginLeft: '5px'}} type="button">Reset</Button>
                        <Button size="large" variant="contained" color="primary" onClick={props.onCancel}
                                style={{marginLeft: '5px'}} type="button">Cancel</Button>
                    </div>
                </Form>
            </div>
        </div>
    )

};

export const CompanyRequestEnhancedFormAbc = withFormik({
    mapPropsToValues: props => {
	
	   //Test the value of fileId. If the value is null, then we need to send 'N' as an asnwer 
        var fileIdValue = sessionStorage.getItem('uploadedFiles') ;  
        console.log("****************************************************************")
        console.log("fileId value from session storage")
        console.log(fileIdValue);
        if(fileIdValue === null){
            console.log("fileId Value is NULL after null check inside const CompanyRequestEnhancedFormAbc");
        }else {
            console.log ("fileId value is not null inside const CompanyRequestEnhancedFormAbc")
        }
	
	
        return {
            createDate: props.testRequest && props.testRequest.createDate || '',
            startDate: props.testRequest && props.testRequest.startDate || '',
            completeDate: props.testRequest && props.testRequest.completeDate || '',
            edwEmployeeId: props.testRequest && props.testRequest.employeeId || '',
            fileId: [sessionStorage.getItem('uploadedFiles')], 
				  
        }
    },
    validationSchema:validationSchema,
    handleSubmit(values, {props, resetForm, setErrors, setSubmitting}) {
              // Do something
    },
    setFieldValue(field, value, shouldVal) {
        console.log('In setFieldValue')
    },

    displayName: 'Company Request Form',
})(CompanyRequestFormAbc)

For the fileId property, you can use a getter operator. That lets you use a function to give the value.

return {
    ...
    get fileId() {
        const uploadedFiles = sessionStorage.getItem('uploadedFiles');
        if (uploadedFiles === null) {
            return ['N'];
        }
        return [uploadedFiles];
    }
};

That way when fileId is accessed, the getter uses the function instead to give the appropriate value.

Thanks @Paul_Wilkins . So I should define this getter operator inside export const CompanyRequestEnhancedFormAbc = withFormik({ block or somewhere else?

The getter is defined as a property on the returned object.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.