M
M
mnq544822022-02-17 21:33:12
JavaScript
mnq54482, 2022-02-17 21:33:12

How to get value from promise?

I make a request to the server https://reqres.in/api/login
My state:

"email": "[email protected]",
    "password": "cityslicka"
    "token":""

And actually, the code itself:
fetch("https://reqres.in/api/login", {
        method: "POST",
        body: JSON.stringify({
          email: state.email,
          password: state.password,
        }),
        headers: { "Content-Type": "application/json" },
      })
        .then((response) => {
          if (response.status !== 200) {
            return Promise.reject();
          }
          return response.json();
        })
        .then(res => state.token = res)


Actually, the question is why the last then does not work as we would like and the state does not change? If you output console.log(res), then the result with the token appears. How can i change the state?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ice, 2022-02-17
@IceRD

https://ru.reactjs.org/docs/hooks-intro.html
Familiarize yourself with the basics of React, namely the useState hook
Error in the correctness of the state change (change by reference does not work)

V
Vladimir, 2022-02-18
@Casufi

The last then works great

fetch("https://baconipsum.com/api/?type=meat-and-filler", )
  .then((response) => {
    if (response.status !== 200) {
      return Promise.reject();
    }
    return response.json();
  })
  .then(res => console.log("res", res))

A piece of code
state.token = res
Doesn't make sense in React Read
how the state changes
https://reactjs.org/docs/state-and-lifecycle.html
https://reactjs.org/docs/hooks-state.html
read the documentation, it's not hard
https://reactjs.org/docs/getting-started.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question