0

This is a very straight forward operation but for some reason the code does not add and remove items from the array as it should.

var [topicList, setTopicList] = React.useState([chipData[0].label]);

  function addTopic(data) {
    if (topicList.indexOf(data.label) > -1) {
      setTopicList(topicList => topicList.filter(topic => topic !== data.label));
    } else {
      setTopicList(topicList => [...topicList, data.label]);
    }
    // Toggle chip UI
    chipData[data.key] = {key: data.key, label: data.label, flag: !data.flag};
    setChipData([...chipData]);
    console.log(topicList);
  }

I would like to add data to the topicList if it's not in the array and remove otherwise.

Nikhil Raghavendra
  • 1,570
  • 5
  • 18
  • 25

2 Answers2

0

Expanding on evolutionxbox's comment: useState is asynchronous and thus you cannot log the newly changed value from the topicList variable.

Rather log the value you are setting to ensure it is correct, and log your topicList variable through useEffect:

function addTopic(data) {
    // your previous code here...
    ...
    console.log(topicList); // rather than logging this
    // do this
    if (topicList.indexOf(data.label) > -1) {
        console.log(topicList.filter(topic => topic !== data.label));
    } else {
        console.log([...topicList, data.label]);
    }
}

And later in the code, you can log out changed variable using useEffect (it works by "observing" changes to variables in square brackets and runs the code inside if this variable changes)

useEffect(() => console.log(topicList), [topicList])
deaponn
  • 837
  • 2
  • 12
  • `useState` is a React hook and is completely synchronous. It returns an array containing the state and a state updater function. This state updater function is ***also*** completely synchronous. What is actually asynchronous is React processing the enqueued state updates. – Drew Reese Aug 23 '22 at 09:17
0

React setState is asynchronous. Which means after setTopicList, you cant directly console.log its state. Because its state might not have been hanged yet.

To log new state, use useEffect. useEffect will watch your state and let you know if it chages.

S4RUUL
  • 141
  • 1
  • 3
  • `setState` is a synchronous function. See my comment [here](https://stackoverflow.com/questions/73454103/unable-to-properly-add-and-remove-items-from-array-in-reactjs?noredirect=1#comment129719966_73454193). – Drew Reese Aug 23 '22 at 09:18