Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React hooks not set state at first time

i have a problem with hooks.

i'm using react-hooks, i have a button which at onClick getting data from api and setState with it.

Problem is:

when i click to button first time i get response from api but can't set it to state. When click to button second time i can setState. Why it happened ?

here is my component look like:

function App() {
  const [a, setA] = useState(null);


  const fetchData = () => {
    let data = {
        id: 1
    }


    axios.post(baseUrl, data)
    .then(res => {
      if (res.data) {
        setA(res.data)
      }
      console.log(a)
    })

  }

  return (
    <div className="App">
      <div>
        <button onClick={fetchData}></button>
      </div>
    </div>
  );
}

export default App;

i tried to using fetchData function like that:

 function fetchData() {
        let data = {
            id: 1
        }


        axios.post(baseUrl, data)
        .then(res => {
          if (res.data) {
            setA(res.data)
          }
          console.log(a)
        })

      }

but it's not helped too

like image 481
user3348410 Avatar asked Oct 29 '25 17:10

user3348410


1 Answers

a is a const. It's impossible to change it, so there's no way your console.log statement at the end of fetchData could ever log out something different than the value that a had when fetchData was created.

So that's not what setA does. The point of setA isn't to change the value of the const, but to cause the component to rerender. On that new render, a new set of variables will be created, and the new a will get the new value. Move your console.log out to the body of your component, and you'll see it rerender with the new value.

In short: Your code appears to be already working, you just have the wrong logging.

like image 84
Nicholas Tower Avatar answered Oct 31 '25 08:10

Nicholas Tower