Help with API/useEffect - React

Asked

Viewed 177 times

0

I need to make a call to the API with React and for that I’m using Axios.

Doing a test with the code below, on the console I can see the result:

const [bill, setBill] = useState([]);

useEffect(() => {
  api.post('/bills', { userId })
    .then(response => console.log(response.data))
    .catch(e => console.log(e));

console.log('bill', bill);
}, []);

inserir a descrição da imagem aqui

But when I try to feed the state the code below, console.log state does not change, remains empty.

const [bill, setBill] = useState([]);

useEffect(() => {
  api.post('/bills', { userId })
    .then(response => {
      setBill(response.data);
    })
    .catch(e => console.log(e));

  console.log('bill', bill);
}, []);

inserir a descrição da imagem aqui

1 answer

2


The state is probably being changed yes. The problem is that you are running the console.log before it is changed.

The status change process in React is asynchronous. Also, how are you working with an asynchronous call (api.post), there is another reason why this state is being changed asynchronously.

See the code:

api.post('/bills', { userId })
  .then(response => {
    setBill(response.data)
  })
  .catch(e => console.log(e));

console.log('bill', bill);

It runs as follows:

  1. First you run the function api.post, which is asynchronous - is returning a Promise.

  2. You perform the console.log, and bill is still a array empty since the state has not been changed.

  3. To Promise is completed, which allows success or failure:

    • In case of failure of the Promise, the callback of catch is executed.
    • In the case of the successful resolution of Promise, the callback of then is executed, which defines the state.

Note that the state is being set after the console.log.

To learn more, try to understand how Promises. A good article to start: "Promises in Javascript: an introduction".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.