-1

Currently working on a create-blog form that requires an input named tags that needs to be an array in my state.

I am using the .push method to push my entries into an empty array that I have in my state.

It works, I am able to create a new blog but there area multiple arrays under tags instead of 1.

Example looks like: ["ne"] ["w] [bl"] ["logs"] instead of just 1 array [new blogs]. Also if I backspace, my previous entries save in the state.

Tried the .push method but it just keeps creating multiple arrays.

state = {
  title: "",
  shortTitle: "",
  content: "",
  shortDescription: "",
  slug: "",
  metaData: {
    dateStart: "",
    section: 0
  },
  statusId: 0,
  primaryImage: "",
  tags: [],
  modal: true
};

handleTags = event => {
  let tags = [...this.state.tags];
  tags.push(event.target.value);
  this.setState({ tags });
};

<FormGroup>
  <Label for="tags">Tags</Label>
  <Input
    type="text"
    name="tags"
    value={this.state.handleTags}
    onChange={this.handleTags}
  />
</FormGroup>;

I can create a blog without any issues if I do not backspace any of my entries. I am hoping to have 1 array for the entry I input in my form instead of multiple ones.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
eneooo
  • 368
  • 3
  • 11
  • 2
    Possible duplicate of [Correct modification of state arrays in ReactJS](https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-reactjs) – Emile Bergeron Aug 06 '19 at 19:24

1 Answers1

2

For one, I don't see this in your state: this.state.handleTags.

I see a function but no variable in your state with that name.

When you do create that state variable, make sure it is not an array.

You could also try deconstructing the tags array like so:

handleTags = event => {
   let tags = [...this.state.tags, event.target.value ];
   this.setState({ tags });
};

Other than that I would need to see more code.

cullanrocks
  • 457
  • 4
  • 16