Mahmoud
Mahmoud

Reputation: 11

react click handler does not work properly

there is a click handler , with 2 statements, and just one of them works, and when I comment out one of them , the other one works properly. the setShowDeleteConfirm is local state . and the setDeleteModal is context. why this happens?. tanx in advance.

<FaTrashAlt onClick={(e) => {
          setShowDeleteConfirm(!showDeleteConfirm);
          setDeleteModal(!deleteModal);
          e.stopPropagation();
          
          }}/> 

Upvotes: 0

Views: 87

Answers (2)

Imran Rafiq Rather
Imran Rafiq Rather

Reputation: 8078

The reason for this is that setState() is asynchronous in Nature, we do not know when one will be executed. That's why this happens.

Suppose you have these two set Functions.

  setShowDeleteConfirm(!showDeleteConfirm);
  setDeleteModal(!deleteModal);

When the setShowDeleteConfirm(!showDeleteConfirm); starts to execute, we cannot predict when it would update the state, as this is asynchronous in nature, the same goes with other case. Cheers !!!

One quick solution I feel is to use callback within the Hook.

<FaTrashAlt onClick={(e) => {
          setShowDeleteConfirm( (prevState) =>{
               return {
                    showDeleteConfirm:!prevState
               }
           } );
          setDeleteModal( (prevState) => {
                return{
                deleteModal:!prevState
               });
           }
          e.stopPropagation(); // I feel this should not be used, it has no purpose here.
          
          }}/> 

Upvotes: 1

Tushar Shahi
Tushar Shahi

Reputation: 20376

When you are updating the state based on previous value it is always better to use the functional pattern. This helps us with a predictable value for the previous state.

 <FaTrashAlt onClick={(e) => {
          setShowDeleteConfirm( showDeleteConfirm => !showDeleteConfirm);
          setDeleteModal( deleteModal => !deleteModal);
          e.stopPropagation();
          
          }}/>   

Upvotes: 0

Related Questions