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?
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.
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}
/>
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With