Home > database >  React, updating array to a new array doesn't re-render the dom with the new array
React, updating array to a new array doesn't re-render the dom with the new array

Time:12-28

so i'm looping over an array, and every element has a click event :

{optionsCategory.map((c,i) => (
     <div className="content" key={i} onClick={(e) => handleCategoryClick(e,c)}>
        {c.name}
     </div>
     ))}

upon clicking if the element has a subCategory i want to assing the subCategory array to the optionsCategory

const handleCategoryClick = async (e: React.MouseEvent<HTMLHeadingElement>, c: Category) => {
if(c.subCategories.length > 0) {
  setOptionsService([...c.subCategories])
  console.log([optionsCategory])
}
else{
  setIsCategory(true);
  const data = await onActsByServiceIdAndCategoryId(serviceId,c.id);
  setActs([...data])
  console.log(acts);
}}

in the console the optionsCategory is updated but not in the Dom

CodePudding user response:

You need to put your optionsCategories inside a useState hook, then react will update the dom, for example: https://jsfiddle.net/7u9cqtxd/

In this case, every two seconds i'll push a new value to optionsCategory and react will update the dom.

const [optionsCategory, setCategory] = useState([30, 20, 10]);
      
setTimeout(() => setCategory([ ...optionsCategory, 50]), 2000);

return (
  <div>
    {optionsCategory.map((category) =>
    <li key={category}>
      {category}
    </li>
  )}
  </div>
);

CodePudding user response:

My bad, after looking at it i used setOptionsService instead of setOptionCategory

  • Related