1

I am trying to push my querySelectorAll .map function to a React State Array but its not working as expected.

const [affectedServices, setAffectedServices] = useState([]);

  function affectedTags() {
    Array.from(document.querySelectorAll(".active-tag")).map((tag) => {
      console.log(tag.innerHTML);
      setAffectedServices([tag.innerHTML]);
    });
  }

console.log(tag.innerHTML) will display all querySelected tags e.g.

Active tag 1
Active tag 2
Active tag 3

But when viewing the affectedServices state from React Dev tools, it only has one array which contains Active tag 3

Any ideas of what im doing wrong?

TIA

0

2 Answers 2

2

Try like this. I think I will works for you.

const [affectedServices, setAffectedServices] = useState([]);

  function affectedTags() {
    setAffectedServices(Array.from(document.querySelectorAll(".active-tag")).map((tag) => {return tag.innerHTML})));
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for your really elegant solution. It works perfectly :)
2

you need to push the value in the array at every loop, and not just replacing the previous value by a new, can you try this ?

useEffect(() => {
  console.log("affectedServices ", affectedServices);
}, [affectedServices]);

function affectedTags() {
    let result = [];

    Array.from(document.querySelectorAll(".active-tag")).forEach((el) => {
      result.push(el);
    });

    setAffectedServices(result);
  }

1 Comment

Thanks for your effort here. its definitely a workable solution for sure :)

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.