Reputation: 23
For example this code:
export const Test = () => {
const [counter, setCounter] = useState(0);
let number;
const DivideByCounter = () => {
number = 10 / counter;
}
const IncreaseCounter = () => {
for(let i = 0; i < 5; i++) {
setCounter(counter + i);
}
}
It's just an example of a code that I'm working on. The problem here is that the setCounter is updating the state correctly, however, when I use the counter to divide, it's returning me Infinity. When I console.log(counter) it's showing me 0, the initial state, however, outside the function, it shows me the updated state. Does everybody know how can I pass the update state into the function so it won't return me Infinity? Thanks in advance :)
Upvotes: 1
Views: 456
Reputation: 1
The Effect Hook lets you perform side effects in function components, in simple words, it means, it lets you run code when state changes or when a prop changes.
you can use UseEffect
to update number
only when there is a change to your counter, or a change to another prop that you want.
const [counter, setCounter] = useState(0);
let number;
useEffect(() => {
DivideByCounter();
console.log(number);
}, [counter]);
const DivideByCounter = () => {
number = 10 / counter;
};
const IncreaseCounter = () => {
for (let i = 0; i < 5; i++) {
setCounter(counter + i);
}
};
you can share how did you try to call DivideByCounter
?
Upvotes: 0
Reputation: 649
You're initial value is set to zero so when you divide for the first time you are dividing by zero which gives infinity
Maybe try adding an exception for zero like the other answer and add a useEffect containing the Divide by counter code and add counter as a dependency
Upvotes: 0
Reputation: 11156
Your problem could be connected to the fact that you call DivideByCounter
before counter
will be updated. Just add a check in DivideByCounter
that, if counter === 0
then number = 0
. Something like:
export const Test = () => {
const [counter, setCounter] = useState(0);
let number;
const DivideByCounter = () => {
if (counter === 0) number = 0;
else number = 10 / counter;
}
const IncreaseCounter = () => {
for(let i = 0; i < 5; i++) {
setCounter(counter + i);
}
}
Upvotes: 1