Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript Array conflicting with React Component

I have three checkboxes that when selected fire a function. I’m using React-Bootstrap and my code is like this:

    let departmentArray = ([]);
    
      function handleCheck(val) {

        //DEPARTMENT ARRAY LOAD
        const index = departmentArray.indexOf(val);
        if (index > -1) {
          departmentArray.splice(index, 1);
        } else {
          departmentArray.push(val);
        }

        //REACT COMPONENT 
        if (val === "Maintenance") {
          setMaintCheck(!maintCheck);
        } else if (val === "Process") {
          setProcCheck(!procCheck);
        } else if (val === "Toolroom") {
          setToolCheck(!toolCheck);
        }

      }; 

  return (
    <>
       <Form.Check name={'department'} onClick={(e) => {handleCheck("Maintenance")}} checked={maintCheck} />
       <Form.Check name={'department'} onClick={(e) => {handleCheck("Process");}} checked={procCheck} />
       <Form.Check name={'department'} onClick={(e) => {handleCheck("Toolroom");}} checked={toolCheck} />
    </>
  )

The state of the checkboxes works with this code, but the array departmentArray does not work if the code underneath //REACT COMPONENT is present. If I remove these lines, the departmentArray loads correctly. I have no idea why the two would be affecting each other.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The departmentArray seems to be a normal var for React, when the code that is under // REACT COMPONENT executes the component rerenders and departmentArray reinitializes to []. You can put departmentArray out of the component as a constant or declare it as a state var for the component reacts to its changes

This is what I mean:

const departmentArray = []

const component = (props) => {

   const loadData = () => {
      // get data from somewhere
      departmentArray.push(...)
   }
   return <></>
}

Or you can declare departmentArray as a state var:

const [departmentArray, setDepartmentArray] = useState([])

const loadDepartments = () => {
   // load data
}

useEffect(loadDeparments, [])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading