Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I execute useEffect even if value (second param) is same as previous value - React

When user choose product type I'm dowloading a file with products which belong to that specific type.

Here is my code:

const [productType, setProductType] = useState(null);

useEffect(() => {
 if (productType!= null) {
      exportProducts();
    }
}, productType); 

My dropdown holds types:

<MyDropdownComponent
  value={productType}
  onChange={e => setProductType(e.target.value)}
  width={200}
/>

I want even if I choose same value twice from a dropdown to download a file again, for example I choose "Sold products", and file is downloaded, immediatly again I choose same thing from dropdown ("Sold products") I want file to be downloaded again, how could I achieve this?

I know hoooks works only if value is changed / different than previous value, than code inside useEffect will render again...

So my question is how could I call code in useEffect even if the value of second parameter is same?

like image 540
Roxy'Pro Avatar asked Jun 14 '26 23:06

Roxy'Pro


2 Answers

You could do it like this:

const [productType, setProductType] = useState(null);
const [productTypeChanges, setProductTypeChanges] = useState(0);

useEffect(() => {
   if (productType !== null) {
       exportProducts();
   }
}, [productTypeChanges]); 

JSX:

<MyDropdownComponent
  value={productType}
  onChange={e => {
      setProductTypeChanges(productTypeChanges + 1);
      setProductType(e.target.value);
  }}
  width={200}
/>

If you want to make sure the render function is being called you need to change either props or state. Since your setProductType is called with the same value, it wont force an render. Maybe there exists a more elegant solution to this, but this is one way to solve this.

You would of course also need to make sure that onChange will be called when the user selects the same value again.

Alternatively you could run your exportProducts in onChange and do not use useEffect at all. But since the question explicitly mentions useEffect this would technically not be a correct answer on its own.

like image 50
Nappy Avatar answered Jun 17 '26 17:06

Nappy


I don't think you need to use useEffect in this usecase

const [productType, setProductType] = useState(null);

const handleChange = e => {
    e.target.value !== null && exportProducts();
    setProductType(e.target.value)
}

return (
<MyDropdownComponent
  value={productType}
  onChange={handleChange}
  width={200}
/>
)
like image 39
Kaslie Avatar answered Jun 17 '26 17:06

Kaslie