1

I'm trying to pass the setter of the parent component to the child component but when I invoked the setter it didn't trigger the parent's useEffect.

const Product = ({ product }) => {
return (
    <div className="border border-black rounded border-2 p-5 flex m-5">
        <div className="w-1/3">
          <p>Name: <span>{product.name}</span></p>
        </div>
        <div className="">
          <p>Price: <span>{product.price}</span></p>
        </div>
    </div>
 )
}

const CreateForm = ({addProduct}) => {
     //renders a POST form for adding product when submit is clicked it triggers 
     //addProduct
}

const Main () => {
   const [products, setProducts] = useState([])
   const fetchData () => {
      fetch("get/products")
      .then(response => response.json())
      .then(data => setProducts(data))

   }

   useEffect(() => {
      console.log("useEffect triggered!")
      fetchData();
   }, [])
   
   const addProduct = (product) => {
      const updatedProducts = [...products, product]
      setProducts(updatedProducts)
   }

   const data = products.map(product => <Product product={product}/>)

   return (
    <div className="m-10">
      <CreateForm addProduct={addProduct}/>

      {data}
    </div>
    )
}

When the submit button is clicked it performs a POST requests creating a product and the addProduct is invoked

zvz
  • 112
  • 6
  • 1
    An empty dependency array will mean the effect runs only on mount. Put the values whose changes you want to listen for inside the dependency array, and then the effect will run when those values change. – CertainPerformance Jun 04 '22 at 01:43

0 Answers0