Home > OS >  React JS Button will not fire off the first time. Always have to click if first
React JS Button will not fire off the first time. Always have to click if first

Time:08-10

Seems like a simple solution, and there is quite a lot of people that have the same question but the solutions don't make any sense to me. Whenever I click the button {rate} consolelogs blank the first time and then gives me a proper number the second time.

Here is the code:

import { useState } from 'react';
import './App.css';

function App() {


  const [from, setFrom] = useState('')
  const [to, setTo] = useState('')
  const [rate, setRate] = useState('')

  const calculate = () => {
  fetch(`https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/${from}.json`)
  .then(response => response.json())
  .then(data => {
    setRate(data[from][to])
    
  })

  console.log(rate)

  }
  

  return (
    <div className="App">
      <div className="container">
      <input type="text" className="from" onChange={(e) => (setFrom(e.target.value))} />
      <input type="text" className="to" onChange={(e) => (setTo(e.target.value))} />
      <button onClick={() => calculate()}>calculate</button>
      </div>
    </div>
  );
}

export default App;

Lmk what you guys think about it! anything will be appreciated. Thank you!

CodePudding user response:

Fetching data and setting state are both asynchronous, so you end up console logging the empty state at first. You can use useEffect to console log the state only when it is changed. P.S. Do not put the useEffect inside your calculate function.

useEffect(() => {
console.log(rate)
}, [rate])

CodePudding user response:

its the common mistake every react beginner does you are thinking that setRate is updating state immediately so you can call rate in the next line setRate is running in async way so when you reach console.log rate is still not updated

what you can do to track a state to detect when it changes is to use useEffect hook you can study here useEffect

NOTE THAT setState functions behave like async functions that executes separately from code sequence

  useEffect(() => {
      console.log(rate)
  },[rate]);
  • Related