Reputation: 9
This function takes arguments {values} and is supposed to calculate a result and set the state of it (in ReactJS). setResult() does not output anything to the console, however, both console.logs output Nan, invalid date, crash my React application and then output the correct values.
const [calcResult, setResult] = useState();
const calculator = (values) => {
let resultSeconds = (values.fileSize*1000)/(values.downloadSpeed/8);
let secondsPure = new Date(null);
secondsPure.setSeconds(resultSeconds);
console.log(secondsPure);
console.log(resultSeconds);
let result = secondsPure.toISOString().substr(11,8);
setResult(result);
console.log(result);
};
For example, let's assume secondsPure = 80. The respective console.log(secondsPure) will print NaN and then, after the React applications crashes, it will print 80 to the console.
Examples for values:
downloadSpeed: "300"
fileSize: "3"
Upvotes: 0
Views: 54
Reputation: 1764
setState is async fucntion which means when you do something like this
const [result , setResult]=useState(null)
const calculator = (values) => {
setResult(result);
console.log(result);//this will output null because setResult call is not done yet
//when setResult finishes you component reloads and only then you can get the new value
};
if you want to get the updated value you need to use useEffect
and set result
as dependency
useEffect(() => {
console.log(result)
}, [result])
Upvotes: 1