0

I am pushing a new item to the array. when a function call."

const tagItem=[];

function handleSelectOption(title, item) {
  setCompareTagTitle(title);
  tagItem.push(item);
  console.log(tagItem)
  if (title !== compareTagTitle) {
    setCounter(++counter);
  } else if (title === compareTagTitle) {
    setCounter(counter);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

when the function call at first time it pushes an item in the array, but when the function calls the second time it looks like it overwrites the item and pushes the new item correctly after that.

This is the photo:

enter image description here

The expected result is:

['c++','php', 'java', 'JavaScript']

But it gives me:

['php', 'java', 'JavaScript']
6
  • 2
    is tagItem just a variable declared at the top level of the component? if so it will be redeclared on each render. If you need it to preserve it's value through renders use a ref or a state. (also push appends items to the end of the array, your expected value seems to indicate appending to the start) Commented Apr 3, 2022 at 9:16
  • 1
    Hi! Please update your question with a minimal reproducible example demonstrating the problem, ideally a runnable one using Stack Snippets (the [<>] toolbar button). Stack Snippets support React, including JSX; here's how to do one. (I doubt Next.js is a factor here.) Commented Apr 3, 2022 at 9:16
  • Thanks for updating the question, but your example still isn't runnable, and still doesn't demonstrate the problem. Commented Apr 3, 2022 at 9:30
  • where was the handleSelectOption called? is it called inside useEffect? Commented Apr 3, 2022 at 9:37
  • 1
    @pilchard you are right, state solved my problem. Commented Apr 3, 2022 at 9:59

1 Answer 1

2

Try adding a local state to your component.

 const [tagItem, setTagItem] = useState([]);

 function handleSelectOption(title, item) {
  setCompareTagTitle(title);
  setTagItem([...tagItem, item]);
  console.log(tagItem)
  if (title !== compareTagTitle) {
    setCounter(++counter);
  } else if (title === compareTagTitle) {
    setCounter(counter);
  }
}


Sign up to request clarification or add additional context in comments.

1 Comment

your answer is correct, but I solved it before as @pilchard directed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.