skip to Main Content

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?

2

Answers


  1. Try to put

    .then(t => setList([t.item]))

    instead of what you wrote

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search