Help with react states

Here’s my code so far -

const [isEmpty, setIsEmpty] = useState(true);
let arr = [];

const addInterviewers = (value, isAdded) => {
   
   if (isAdded === 'ADD') {
     arr.push(value);
   } else {
     const index = arr.indexOf(value);
     arr.splice(index, 1)
   }
   
   enableButton();

   console.log(isEmpty);
   console.log(arr);
 }

 const enableButton = () => {
  if (arr.length === 0) {
    setIsEmpty(true);
  } else {
    setIsEmpty(false);
}  
}
   

<button
  className={
	isEmpty
	    ? "Interviewers-button"
	    : "Interviewers-button-enabled"
	}
> 
Next&emsp;&ensp; <FontAwesomeIcon icon="chevron-right"/>
</button>

The problem is, enableButton function is interfering with array ‘arr’ values. Because of enableButton, arr removes the first element and starts with second element.

Sorry for bad explanation. I hope it makes sense.

1 Like

I would need to see more of the code. Do you have a repo?

Yes thanks! Here - https://gitlab.com/Suraj-Mishra/feedback-app

Why is that array (arr) not being held in useState? Every time that component rerenders, it’s an empty array again, yet it seems like you’re trying to use it statefully: the handler that makes use of it is passed onto another component.

I solved the problem. Here’s the new code -

const [isEmpty, setIsEmpty] = useState(true);
  const [arr, setArr] = useState([]);

 const addInterviewers = (value, isAdded) => {
   
   if (isAdded === 'ADD') {
     let newList = arr;
     newList.push(value);
     setArr(newList);
   } else {
     let newList = arr;
     const index = newList.indexOf(value);
     newList.splice(index, 1);
     setArr(newList);
   }
   enableButton();
   console.log(isEmpty);
   console.log(arr);

   LocalForage.setItem('Name', arr);
 }

 const enableButton = () => {
  if (arr.length === 0) {
    setIsEmpty(true);
  } else {
    setIsEmpty(false);
}  
}