Search code examples
javascriptreact-nativeasyncstorage

React Native AsyncStorage won't fetch on first try


Im getting this behaviour when trying to show data saved to AsyncStorage: http://sendvid.com/5ash8vpu

Relevant code:

screen1:

class VerMais extends Component {

  constructor(props) {
    super(props);
    this.state = {
      data: '',
      value: [],
    };
  }

  componentWillMount(){
    AsyncStorage.getItem('key').then(JSON.parse).then(items => {
      this.setState({value: items});
    })

    financiamentoAPI.getTextos().then((res) => {
      this.setState({
        data: res.Zona
      })
    });
  }

  render() {
    return (
      <View style={{ flex: 1 }}>
        {this.renderWarning()}
        <NavigationBar
          tintColor='#1f1f1f'
          statusBar={{style: 'light-content'}}
          title={<NavbarTitle/>}/>
        <View style={styles.container}>
          <View style={styles.botaoContainer}>
            <TouchableOpacity onPress={() => this.props.navigation.navigate('Financiamento', { data: this.state.data })} style={styles.botaoPrimeiro}>
              <Icon style={styles.icon} size={10} name={'circle'} color={'#f48529'}/><Text style={styles.texto}>  Financiamento</Text>
            </TouchableOpacity>

            <TouchableOpacity onPress={() => Communications.web('http://www.consilbuy.pt/')} style={styles.botaoPrimeiro}>
              <Icon style={styles.icon} size={10} name={'circle'} color={'#f48529'}/><Text style={styles.texto}>  Venda Já!</Text>
            </TouchableOpacity>

            <TouchableOpacity onPress={() => this.props.navigation.navigate('Favoritos', { value: this.state.value })} style={styles.botaoNoBorder}>
              <Icon style={styles.icon} size={10} name={'circle'} color={'#f48529'}/><Text style={styles.texto}>  Favoritos e Alertas</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    );
  }

screen2:

const flatten = arr => arr.reduce(
  (acc, val) => acc.concat(
    Array.isArray(val) ? flatten(val) : val
  ),
  []
);

export default class Favoritos extends Component {

  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      value: this.props.navigation.state.params.value,
    };
  }

  componentWillMount(){
    this.setState({ isLoading: true});
    this.getData();
  }

  getData(){
    if(!this.state.value == 0 || !this.state.value == null){
      const promises = this.state.value.map((item, index) =>
        fetch(`URL/portalacv_ws.asmx/GetDetalhesViatura?CarID=${item}`)
         .then(response => response.json())
      )
      Promise.all(promises).then(values => this.setState({values: flatten(values), isLoading: false}))
    }
    this.setState({values: null, isLoading: false})
  }

  render() {
    const {goBack, navigate} = this.props.navigation;
    if(this.state.isLoading === true)
    {
      return(
        <View style={{ flex: 1, backgroundColor: 'white' }}>
          <NavigationBar
            tintColor='#1f1f1f'
            statusBar={{style: 'light-content'}}
            title={<NavbarTitle/>}
            leftButton={
              <NavbarLeft
                onPress={() => goBack()}
              />}
          />
          <ActivityIndicator size='small' style={{padding: 100}}/>
        </View>
      );
    }

    if(this.state.values == 0 || this.state.values == null)
    {
      return(
        <View style={{ flex: 1, backgroundColor: 'white' }}>
          <NavigationBar
            tintColor='#1f1f1f'
            statusBar={{style: 'light-content'}}
            title={<NavbarTitle/>}
            leftButton={
              <NavbarLeft
                onPress={() => goBack()}
              />}
          />
          <View style={{ flex: 1, alignItems: 'center', flexDirection:'row', justifyContent:'center'}}>
            <Text style={styles.text2}>
              Ainda não adicionou nenhuma viatura aos favoritos!
            </Text>
          </View>
        </View>
      );
    }
    return (
      <View style={{ flex: 1, backgroundColor: 'white' }}>
        <NavigationBar
          tintColor='#1f1f1f'
          statusBar={{style: 'light-content'}}
          title={<NavbarTitle/>}
          leftButton={
            <NavbarLeft
              onPress={() => goBack()}
            />}
        />
        <View style={styles.container}>
          <FlatList
            removeClippedSubviews={false}
            data={this.state.values}
            keyExtractor={item => item.CodViatura}
            renderItem={({item}) => (
              <TouchableWithoutFeedback onPress={() => navigate('FichaFavoritos', { codigo: item.CodViatura })}>
               //DATA TO RENDER
              </TouchableWithoutFeedback>
            )}
          />
        </View>
      </View>
    );
  }
}

Screen1 is the one where I click "Favoritos e Alertas" and Screen 2 is the screen where it only shows the car on second try. Does anyone know why it is not showing the car when I first open the screen?


Solution

  • I found what I was doing wrong. I was fetching my local data when my component is mount, so adding new cars to favorites won't show because component was already mounted so it wouldn't fetch the data again.

    I had to do the fetch when I click the button to open favorites screen and only then navigate to the screen. Like this:

      fetchAsync(){
        AsyncStorage.getItem('key').then(JSON.parse).then(items => {
          this.setState({value: items});
          this.props.navigation.navigate('Favoritos', { value: this.state.value })
        })
      }
    

    and on the button just set the onPres:

    onPress={() => this.fetchAsync()}