[SOLVED] Can't add object to existing array (useState react native)


I have addText() that runs on click event

const [list, setList] = useState([])
const [value, setValue] = useState("")

useEffect(() => {
        .then(t => setList(t.item))
        .catch(e => { console.log(e) })
}), []
// A function that add data to the list array

function addText(text) {
    if (value !== "") {
        setList(prev =>
            { text: text, isSelected: false }] // Adding a JS Object

        setObjectItem("tasks", list);
    } else {
        alert("Please type in something!")

Output from console.log(list):

  Array [
          Object {
            "isSelected": true,
            "text": "Test",

getObjectItem("tasks") 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?


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.

Answered By – Dave Newton

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.