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

Issue

I have addText() that runs on click event

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

useEffect(() => {
    getObjectItem("tasks")
        .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("tasks", list);
        setValue("")
    } 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?

Solution

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.