react-nativereact-native-flatlistasync-components

To save the data onpress of item in a asycstorage in react native


I'm trying to display the time zone in another screen when an item is pressed in previous flatlist. My data is coming from autocomplete when I'm selecting it is displayed in flatlist.

<Autocomplete
      autoCapitalize="none"
      autoCorrect={false}
      containerStyle={styles.autocompleteContainer}
      data={autotime.length === 1 && comp(query, autotime[0].name) ? [] : autotime}
      defaultValue={this.state.timeZone}
      onChangeText={text => this.setState({ query: text })}
      placeholder="Enter Location"
      renderItem={({ name, release_date }) => (
        <TouchableOpacity onPress={() => this.setState({ query: name,timezoneArray:autotime[0].timezones })}>
          <Text style={styles.itemText}>
            {name}
          </Text>
        </TouchableOpacity>
      )}
    />
    <View style={styles.descriptionContainer}>
    {autotime.length > 0 ? (
      <FlatList
      style={{flex:1}}
      data={this.state.timezoneArray}
      renderItem={({ item }) => <TimeZoneItem text={item} />}

    />

      ) : (

        <Text style={styles.infoText}>Enter Location</Text>

)}

I want that when I press the items of flatlist it is displayed on another page.

Picture below shows what I have made: enter image description here

My Data base helper class is:

export const SaveItem = (key, value) => {
AsyncStorage.setItem(key, value);
};

export const ReadItem = async (key) => {
try {
    var result = await AsyncStorage.getItem(key);
    return result;
 } catch (e) {
    return e;
 }
 };

 export function MultiRead(key, onResponse, onFailure) {
 try {
    AsyncStorage.multiGet(key).then(
        (values) => {
            let responseMap = new Map();
            values.map((result, i, data) => {
                let key = data[i][0];
                let value = data[i][1];
                responseMap.set(key, value);
            });
            onResponse(responseMap)
        });
 } catch (error) {
     onFailure(error);
 }
 };

export async function DeleteItem(key) {
try {
    await AsyncStorage.removeItem(key);
    return true;
}
catch (exception) {
    return false;
}
}

and here i have added my code to save

 handleTimezone = (text) => {
  this.setState({ TimeZoneItem: text })
 }
  newData.TimeZoneItem = this.state.TimeZoneItem
  this.setState({
 TimeZoneItem: '',
})   
 ReadItem('timeData').then((result) => {
  let temp = []
  if (result != null) {
    temp = JSON.parse(result)
  } else {
    temp = []
  }
  temp.push(newData)
  SaveItem('timeData', JSON.stringify(temp))
  console.log(`New Data: ${JSON.stringify(temp)}`)
  }).catch((e) => {

  })
  }
  <FlatList
      style={{flex:1}}
      data={this.state.timezoneArray}
      renderItem={({ item }) => (
      <TouchableOpacity>
      <TimeZoneItem text={item} onPress={() => this.props.onPress()}
      value={this.state.TimeZoneItem}

      />
      </TouchableOpacity>)}

Solution

  • You'll need an array to saved all the saved items.

    for example

    state = {
      saved: []
    };
    

    On press the time zone item, get the values from state, add the new item to the array and save the array to async storage using JSON.stringify()

    onSave = item => {
    
        const { saved } = this.state;
        const newItems = [...saved, item];
    
        this.setState({
        saved: newItems
        });
    
        const items = JSON.stringify(newItems);
    
        SaveItem("saved", items)
        .then(res => {
            console.warn("saved", res);
        })
        .catch(e => console.warn(e));
    };
    

    Then in your other screen get the items in using your ReadItem function like.

    state = {
        saved: []
    };
    
    componentDidMount = () => {
        ReadItem("saved")
        .then(res => {
            if (res) {
            const saved = JSON.parse(res);
            this.setState({
                saved: saved
            });
            }
        })
        .catch(e => console.warn(e));
    };
    

    Working Demo