Home > database >  The useState set method not rendring the specific component
The useState set method not rendring the specific component

Time:01-31

I want to update my TaskDetail (at Right Side) component with new card data but when I change the value of card from handleCardClick callback it does not reflect the change to that specific component. If you look at attached gif you will see that useEffect is getting the updated values of card and the page variable in the same call back showing updated value on view.

enter image description here

Here is the minimum code that depict my problem.

 const [selectedCard, setSelectCard] = useState(null);
  const [selectedColumn, setSelectedColumn] = useState(null);
  // Page Updater
  const [page, setPage] = useState(0);


  const handleCardClick = (e, card, columnId) => {
    
    setSelectedColumn(columnId);
    setSelectCard(card);
    setPage(page   1);
    
  }


  useEffect(() => {
    // action on update of movies
    console.log(selectedCard);
    console.log(selectedColumn);
    
}, [selectedCard]);


return (
    <Container>
      <DragDropContext onDragEnd={handleDragEnd}>
        {boardData.map((list) => (
          <List key={list.title} column={list} handleAddTask={handleAddTask} handleCardClick={handleCardClick} />
        ))}
      </DragDropContext>
      <p>{page}</p>
      <> {(page !== 0) && <TaskDetail card={selectedCard} columnId={selectedColumn} />}</>

    </Container>
  );

This is the most relevant to my question The useState set method is not reflecting a change immediately but I did't find the solution from it.

CodePudding user response:

I would try 2 things:

  1. Check the TaskDetail code to see if it has state management of it's own. If it does, you need to make sure it triggers re-render when the relevant props change (trigger it by calling setState inside the component for example)
  2. Add a unique key to the TaskDetail component to force it to re-render when the key changes. For example:
<TaskDetail key={selectedCard.id} card={selectedCard} columnId={selectedColumn} />
  • Related