W
W
WhatYouDoing2019-12-11 18:14:46
JavaScript
WhatYouDoing, 2019-12-11 18:14:46

How to write a value to state?

How to write value when didMount from async storage to state?

constructor(props) {
    super(props);
    this.state = {
      access_token: '',
    };
  }

  componentDidMount() {
    AsyncStorage.getItem('access_token').then(value => {
      this.setState({access_token: value});
    });

    console.log(this.state.access_token);
  }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Osher, 2019-12-11
@miraage

Apparently you have a gap in the asynchronous JS model.
In your case, something like this happens:

--- internal tick
- componentDidMount
- asyncStorage.getItem
- console.log // на этот момент мы ещё не попали в then
--- internal tick
- then блок
- setState

To read the token, you must either:
- pass callback as the second parameter to setState, which will be called after the state has been updated, and call console.log there already
- call consoe.log in componentDidUpdate

A
Aetae, 2019-12-11
@Aetae

The answer to your question is: you are already doing it, everything is in order.
The answer to the question "how to read the value from the state after writing it when didMount" was given by Mikhail Osher .:)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question