i have to make a few changes in a project and i'm not really familiar with react. How can i change the state of a Hook from an outside function? This is what i have:
export const HomeView = () => {
[...]
const ProductDetails = () => {
const [number, setNumber] = React.useState(0);
const [currentPrice, setCurrentPrice] = React.useState(5);
React.useEffect(() => {
const fetchData = async () => {
// get available items and current price when page loads
[...]
const number = 15;
setNumber(number);
[...]
const currentPrice = 10;
setCurrentPrice(currentPrice);
};
fetchData();
}, []);
// returns available items and current price with a button to buy
return (
<div >
<h2>Current price : {currentPrice} </h2>
<button onClick={() => buyProduct({currentPrice})}>
"Click me"
</button>
<h2>Available {number} / 10000</h2>
</div>
);
const buyProduct = async ({currentPrice}: {currentPrice: number;}) => {
//users buys product, refresh available number
[...]
const number = 14;
//each time a buy occurs, i have to increase price
const currentPrice = 11;
//How do i pass this new data to update the data in ProductDetails when a buy occurs without
//refreshing the whole page from the browser?
};
return (
<div >
[...]
<ProductDetails />
[...]
</div>
);
I thought about moving the hook from ProductDetails inside the whole HomeView, but i don't really know how the whole process will work since i'm not that familiar with react. Thanks in advance for your help.