1

Hi i have this wierd problem in which i can access property ooPPon state object but can not access property data of state objects. the only difference is how they are populated.

  • state.ooPP is hardcoded
  • state.data is set after calling few functions .

i can see value of state.data as array with one element in react native dev tools but why is this.state.data null in render()?

here is the code:

   export default class HomeScreen extends Component {

      _retrieveData = async key => {
        try {
          const value = await AsyncStorage.getItem(key);
          if (value !== null) {
            // We have data!!
            console.log("yay....", value);
            return value;
          }
        } catch (error) {
          // Error retrieving data
        }
      };

      getAllKeys = async () => {
        let keys = [];
        try {
          keys = await AsyncStorage.getAllKeys();
        } catch (e) {
          // read key error
        }

        return keys;
      };



      constructor(props) {
        super(props);

        this.state = {
          data:[],
          kk:'oo',
          ooPP:[{'username':'uuuuu'}]
        }

        this.getAllKeys().then(keys => {
          var promises = keys.map(key => {
            return this._retrieveData(key)
              .then(value => {
                console.log(value, "xx");
                return JSON.parse(value);
              })
              .catch(error => {
//
              });
          });

          Promise.all(promises)
            .then(results => {
              this.state.data=results
            })
            .catch(e => {
//
            });
        });
      }



      renderSeparator = () => {
        return (
          <View
            style={{
              height: 1,
              backgroundColor: "#CED0CE"
            }}
          />
        );
      };

      render = () => {
        return (
          <View>
            <FlatList
              data={this.state.data} //-------> this is not accessible
              ItemSeparatorComponent={this.renderSeparator}
              renderItem={({ item }) => (
                <TOTPItem value={item.username} time={(20 / 30) * 100} />
              )}
            />
            <Text>dd {this.state.kk}</Text>
          </View>
        );
      }
    }
3
  • 1
    If you don't use setState like you're supposed to, React isn't going to re-render the component. You're still changing this.state obviously, because React is just JavaScript, but if you insist on ignoring the docs, don't expect React to behave as expected. Commented Jun 27, 2019 at 21:09
  • @ChrisG i am not ignoring the docs. i started react native/react learning today.also i am a backend dev so i just missed it. anyways thannks for help its working now :) Commented Jun 27, 2019 at 21:13
  • 1
    I was responding to i am updating state in constructor so setState() is not the correct way but I see now where the confusion was coming from :) Commented Jun 27, 2019 at 22:34

1 Answer 1

3
Promise.all(promises)
  .then(results => {              
    this.setState({data: results});
  })
  .catch(e => {
    //
  });
});

You need to use setState to update state.

Sign up to request clarification or add additional context in comments.

4 Comments

i am updating state in constructor so setState() is not the correct way. also if state is not updated then how is it visible in dev tools?
holy cow! thanks. this is working. i had been scratching my head for entire day before giving up on this.
In constructor, we just initialize the state variable. we do not update there. Use ComponentDidMount() to update state.
Of note: setState is an async action, so after it returns, the state is not guaranteed to have changed yet. If you need to wait on the state to change, then pass a callback to setState. This would be especially important if you were to continue chaining promises after setState...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.