V
V
vimirtv2018-08-21 15:44:42
API
vimirtv, 2018-08-21 15:44:42

How to write API requests in react native?

I'm trying to make a query like this

componentWillMount () {
    fetch('http://registry.domen.ru:5002/Profile/Authorize', { 
      method: 'POST', 
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        "userName": this.props.userName,
        "token": this.props.token
      })
    })
    .then((res) => {
      res.json().then((json) => {
        console.log('Получили токен',JSON.stringify(json.data.bearer))
      })
    })
    .catch((err) => {
        console.log(JSON.stringify(err))
}
    })


Then render is executed

render() {
    console.log('Готово')
    return (<Text>ПРИМЕР</Text>)
}


Why does console.log('Done') execute before console.log('Got a token',JSON.stringify(json.data.bearer)) ?
How to get the response first and then execute the render

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dimka Reactive, 2018-08-22
@raoffonom

Why does console.log('Done') execute before console.log('Got a token',JSON.stringify(json.data.bearer)) ?
The first componentWillMount is already deprecated and will be deprecated in future versions. API requests must be made in componentDidMount()
Secondly, the React component has a lifecycle:

constructor() // console.log('Done')
static getDerivedStateFromProps()
render()
componentDidMount() // console.log('Received token',JSON.stringify(json.data.bearer))

static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
componentWillUnmount()

I made a video about the life cycle in more detail

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question