Home > Blockchain >  How to push an object to the dict state?
How to push an object to the dict state?

Time:10-10

I'm trying to push an object to the state.

I created a function for this. This function should copy the first state object and add it to the end of the state.

addField() {
    const newFields = [...this.state?.fields[3]]

    console.log("newFields", newFields) // [    {        "key": "input_field_name",        "value": "This is a value 4"    },    {        "key": "field_name",        "value": "field name's value 4"    },    {        "key": "datatype",        "value": "text"    },    {        "key": "Datatype",        "value": "Label 4"    }]

   
    const index = (this.state?.fields.length)   1

    this.setState(
      { 
        fields: {...this.state.fields[index], newFields},
      },
      () => {
        console.log("updated state", this.state);
      }
    );
    console.log("state: ", this.state)

But it is giving error in
fields: {...this.state.fields[index], newFields}

type '{ newFields: any[]; length: number; toString(): string; toLocaleString(): string; pop(): IFieldDefinition | undefined; push(...items: IFieldDefinition[]): number; ... 29 more ...; Symbol.unscopables: { ...; }; }' is not assignable to type 'IFieldDefinition[][]'. Object literal may only specify known properties, and 'newFields' does not exist in type 'IFieldDefinition[][]'

This is my state:

fields: IFieldDefinition[][];
  activeFields: {
    key: number;
    fields: IFieldDefinition[];
  };

this.state

how can I do that?

CodePudding user response:

fields is an array, so you cannot assign values as an object with {}

If you want to add that new state to the end of the state, you can use the below approach

const newFields = [...this.state?.fields[3]];

//if the current index is matched with which field you want to update (you use index `3`)
//we will append `newFields` on the current value by `[...]`
this.setState(
  {
    fields: this.state.fields.map((currentValue, currentIndex) =>
      currentIndex === 3 ? [...currentValue, ...newFields] : currentValue
    ),
  },
  () => {
    console.log("updated state", this.state);
  }
);
console.log("state: ", this.state);

CodePudding user response:

Do you want to remove the 0th index data and move it to the end of the array if so


let a={A:[{a:1},{b:2},{c:3}]}
let temp=a.A.shift()
a.A.push(temp)
setState({...a})

  • Related