Home > Software engineering >  javascript push function is not working as expected. I am trying to push data to array or list
javascript push function is not working as expected. I am trying to push data to array or list

Time:11-27

Can you explain why the code block 1 is not working and how is it that code block 2 works I am trying to add the data of my placeholder to the data of my storage.

  const [placeholder, setPlaceholder] = useState([
    {
      id: 0,
      title: null,
      icon: null,
      UUID: null,
      Children: [],
      action: null,
    },
  ]);

code block 1

  const jsonValue = await AsyncStorage.getItem('@custom_layout');
  
  if (JSON.parse(jsonValue) != null) {
    JSON.parse(jsonValue).push(placeholder[0]);
    console.log(JSON.parse(jsonValue));
  }

code block 2


    const jsonValue = await AsyncStorage.getItem('@custom_layout');
    const myData = JSON.parse(jsonValue);
    if (JSON.parse(jsonValue) != null) {
      JSON.parse(jsonValue).push(placeholder[0]);
      console.log(JSON.parse(jsonValue));
    }

CodePudding user response:

The problem is here:

JSON.parse(jsonValue).push(placeholder[0]);
console.log(JSON.parse(jsonValue));

This likely does add add placeholder to the jsonValue, but it does not assign it or modify jsonValue.

Instead:

const output = JSON.parse(jsonValue).push(placeholder[0]);
console.log(output);

In steps:

const obj = JSON.parse(jsonValue);
obj.push(placeholder[0])
console.log(obj);

edit: if code block 2 does indeed work then this is not correct. I think it's more likely that code block 2 is console logging the assigned value placeholder[0].

  • Related