Asyncstorage with dynamic keys does not save values

Asked

Viewed 178 times

-1

I’m trying to make a list where the user sees all the Keys he saved in the app and when he clicks on them will occur the load of the preset he made based on the key. I’m getting the bug:

Typeerror: Attempted to assign to readonly Property

    state = {
        dateiName: 'Mrx',
        dateiDatum: '',
        dateiAuto: '',
        dateien: [],
        dateiselected: '',
        arr: []
    }

    async componentDidMount() {
        var listData = [];
        let keys = await AsyncStorage.getAllKeys();
        keys.forEach(async function(inKey) {
          const person = await AsyncStorage.getItem(inKey);
          person.key = inKey;
          listData.push(person);
        });
        this.setState({arr: listData})
        console.log(arr)
      };

     saveData(nome) {
        var nomeKey = nome
        AsyncStorage.setItem(nomeKey,JSON.stringify(this.state.arr))
     }

    displayData = async () => {
        try{
            const keys = await AsyncStorage.getAllKeys();
            return keys
        }
        catch(error) {
            alert(error)
        }
    }


    removeData = async () => {
        try {
          await AsyncStorage.clear()
          alert('Storage successfully cleared!')
        } catch (e) {
          alert('Failed to clear the async storage.')
        }
      }

    render(){
        return (
            //aqui vem algumas coisas irrelevantes antes
            <>
                <ScrollView>
                    <FlatList
                        data={this.state.arr}
                        renderItem={({item}) => (
                            <View>
                                <TouchableOpacity>
                                    <Text>{item}</Text>
                                </TouchableOpacity>
                            </View>
                        )}
                        //keyExtractor={item => item.id}
                    />
                </ScrollView>
                <TouchableOpacity
                    onPress={this.saveData(this.state.dateiName)}
                    style={styles.botaomenor}>
                </TouchableOpacity>
            </>
        );
    }

1 answer

0

Hello! It’s not ideal for you to put async in the componentDidMount you could create an asynchronous function and call it in. I believe the error is due to:

person.key = inKey;

I think this result is read-only even if you use it as an object. You are not using this attribute in any corner only within this scope so neither is it necessary to create it can pull out and use something like this:

listData.push({
  key: inKey,
  person,
});

One remark, I don’t know how your logic is when saving the data, but instead of saving each user individually in asyncstorage it would not be better to save an array of users there?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.