I am working with these notes using AsyncStorage, my issue comes after I concat the new data, it gets added as nested object, that’s not what I expected so the code looks like
addNote = async () => { try { var id = this.props.navigation.state.params.data.vhq_id; var raw = await AsyncStorage.getItem("notes"); var value = JSON.parse(raw); if (value === null) { await AsyncStorage.setItem( "notes", JSON.stringify({ text: this.state.userinput, id: id }) ); } else { var note = { text: this.state.userinput, id: id, }; var newData = { value, note }; await AsyncStorage.setItem("notes", JSON.stringify(newData)); } } catch (erorr) { console.log(error.message); } };
The output I have
Object { "note": Object { "id": "c62eb2fe-1647-4e9e-ad21-ce0fb0216948", "text": "Cccc", }, "value": Object { "note": Object { "id": "c62eb2fe-1647-4e9e-ad21-ce0fb0216948", "text": "Bbbb", }, "value": Object { "id": "c62eb2fe-1647-4e9e-ad21-ce0fb0216948", "text": "Aaaa", }, }, }
I am not sure why this is happening, I tried adding the object directly on the concat function without using it as variable but it seems it’s the wrong syntax
var newData = { value, {text: this.state.userinput, id: id} };
Advertisement
Answer
I think you want notes
to be an array and if theres already a note in AsyncStorage
you want to append a new note to the array. So you might want to try this
addNote = async () => { try { var id = this.props.navigation.state.params.data.vhq_id; var raw = await AsyncStorage.getItem("notes"); var value = JSON.parse(raw); if (value === null) { await AsyncStorage.setItem( "notes", JSON.stringify([{ text: this.state.userinput, id: id }]) // See that this is setting an array item to the notes ); } else { var note = { text: this.state.userinput, id: id, }; var newData = [ ...value, note ]; // newData is a new array with all items in the value array plus the new note object await AsyncStorage.setItem("notes", JSON.stringify(newData)); } } catch (erorr) { console.log(error.message); } };