I have addText() that runs on click event
const [list, setList] = useState([])
const [value, setValue] = useState("")
useEffect(() => {
getObjectItem("task")
.then(t => setList(t.item))
.catch(e => { console.log(e) })
}), []
// A function that add data to the list array
function addText(text) {
console.log(list);
if (value !== "") {
setList(prev =>
[...prev,
{ text: text, isSelected: false }] // Adding a JS Object
)
setObjectItem("task", list);
setValue("")
} else {
alert("Please type in something!")
}
}
Output from console.log(list):
Array [
Object {
"isSelected": true,
"text": "Test",
}
]
getObjectItem("task") function:
const getObjectItem = async (name) => {
try {
const jsonItem = await AsyncStorage.getItem(name)
const item = JSON.parse(jsonItem)
return {
status: 'success',
name: name,
item: item
}
} catch (err) {
return {
status: 'error',
name: name,
error: err
}
}
}
Why can't I add values to the existing list
array with setList()
in addText() function?
CodePudding user response:
Try to put
.then(t => setList([t.item]))
instead of what you wrote
CodePudding user response:
Setting state is asynchronous.
In addText
you write:
setObjectItem("task", list)
which will set the value in AsyncStorage
to whatever list
was, not what it will be after the state has been updated. The easiest solution is to create the new array then set it to state and AsyncStorage
.