简体   繁体   中英

storing values in an array using react usestate hook

I have the following formik based example where I'm using primereact fileupload. Everytime user uploads a file, the value of selectedAssetCategoryId is different. If a user is uploading multiple file at once then the value will remain the same. For example, if a user is uploading 3 files together, the value of selectedAssetCategoryId will be 1.

So I want to store value 1 three times in uploadedFileCategory array.

Is setUploadedFileCategory(uploadedFileCategory =>[...uploadedFileCategory,selectedAssetCategoryId]); a correct way of pusing items in the array? When I'm hovering over the variable uploadedFileCategory on this line const [uploadedFileCategory, setUploadedFileCategory] = useState([]) , visual studio code editor is telling me that uploadedFileCategory is declared but its value is never read.ts(6133)

const DataRequestForm = (props) => {
    const user = JSON.parse(sessionStorage.loggedInUser)
    const {values, setFieldValue, touched, errors, isSubmitting, handleReset, handleChange} = props;
    const growl = React.createRef()
    
     const [uploadedFileCategory , setUploadedFileCategory] = useState([])

    
    
    // fileUpload function testing using new service
    const fileUpload = (e) => {
      

         //Store the values in an array.
         setUploadedFileCategory(uploadedFileCategory =>[...uploadedFileCategory,selectedAssetCategoryId]);
      
        const personnelId = JSON.parse(sessionStorage.loggedInUser).id
        let formData = new FormData();
        e.files.forEach((file, i) => formData.append(`files`, file))

        axios.post('upms/uploadAndCreateAssociations?personnelId=' + personnelId +'&assetCategoryId='+selectedAssetCategoryId, formData,{
            headers: {
                "Content-Type": "multipart/form-data"
            }
        }).then((response) => {
            
            }).catch(err => console.log(err));


        }).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">
                <Growl ref={growl}/>
                <Form className="form-column-3">
                                         
                         
                    <div className="datarequest-form">   
                     <label style={{marginRight: '1355px',fontWeight: 'bold'}}>Document Upload</label>
                   
                    <div className="form-field">
                                <FileUpload
                                    name="files"
                                    mode='advanced'
                                    uploadHandler={fileUpload}
                                    customUpload={true}
                                    chooseLabel="Attach Files"
                                    maxFileSize="2058722381"
                                    ref={fileUploadRef}
                                    id="researcherAttachFileButton"
                                    disabled={disableButton}
                                    multiple={true}/>   
                                   
                             </div>

                       
                      
                       
                    </div>
                </Form>
            </div>
        </div>
    )

};

export const DataRequestEnhancedForm = withFormik(
    
    
    
    {

        
    mapPropsToValues: props => {

              
        
        return {
            
            uploadedFileCategory: uploadedFileCategory
            
        }
    },
    validationSchema:validationSchema,
    handleSubmit(values, {props, resetForm, setErrors, setSubmitting}) {
      
        props.handleSubmit(values)
      
        setSubmitting(false)
    },
    setFieldValue(field, value, shouldVal) {
        console.log('In setFieldValue')
    },

    displayName: 'Data Request Form',
})(DataRequestForm)

Let me answer this:

Question 1:

Is setUploadedFileCategory(uploadedFileCategory =>[...uploadedFileCategory,selectedAssetCategoryId]); a correct way of pusing items in the array?

Answer It works and here is the example code:

import "./styles.css";
import { useState } from "react";

export default function App() {
  const [array, setArray] = useState([]);
  const changeArray = () => {
    console.log(array);
    setArray((b) => [...array, 1]);
  };
  return (
    <div className="App">
      <h1>Open console to see the logs</h1>
      <button onClick={() => changeArray()}>Example</button>
    </div>
  );
}

The link is currently live at: https://byy0g5.csb.app/ Look at the console to see the logs.

Question 2

When I'm hovering over the variable uploadedFileCategory on this line const [uploadedFileCategory, setUploadedFileCategory] = useState([]), visual studio code editor is telling me that uploadedFileCategory is declared but its value is never read.ts(6133)

Answer It simply means that uploadedFileCategory is not being used anywhere in the code.

Even if the value is correctly set, you need to properly place this in the code to see the changes of value. Try console.log(uploadedFileCategory) to see the output of the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM