Home > Blockchain >  changing state with Array.map doesn't update state
changing state with Array.map doesn't update state

Time:11-07

I am mapping through an array like this

const isFocused = useIsFocused();

async function getProfile() {
const [labels, setLabels] = useState([])
...

array.map(x => {
            handleChange(x.date)
          })
...
    }

useEffect(() => {
    isFocused && getProfile()
  }, [isFocused]);

The code for handleChange()

function handleChange(date) {
    console.log(date,"THIS IS DATE IN HANDLE")
    setLabels([...labels, date])
  }

The value of label after this is only the last index of the array. How do I fix this issue?

CodePudding user response:

You can't mutate state directly. You need to make a copy of the state and then mutate the copy.

CodePudding user response:

I would suggest you to use an temporary array to store the gathered result first then set the state.

Since setState in React is asynchronous, the program may get the state which is not updated (Always empty) until the last setState.

const [labels, setLabels] = useState([])

let temp = [...labels];   //Get Any pre-stored items
array.map(x => {
  console.log(date,"THIS IS DATE IN HANDLE")
  temp.push(labels);
})

setLabels(temp);
  • Related