3

React newbie, This is very basic form submit but what I am trying to do here is create array from the value received from the input then and setState with array but before setState also remove any duplicates in the array.

import React, { Component } from 'react';

class Chase extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ''
    };
  }
  handleSubmit = (e) => {
    e.preventDefault();
// Should I create array in the handlesubmit ?
  };

  handleChange = (e) => {
      e.preventDefault()
      let newspoo = e.target.value
      let createArr= newspoo.split(' ')
      let newVal = Array.from(new Set(createArr))
       this.setState({ newVal}, () =>{
        console.log(newVal)
    });
// this works in console but on display I cannot see any values in the UI
  };

  render() {

    const {value} = this.state
    return (
      <form onSubmit={this.handleSubmit}>
       <div>
       <label>
          Name:
          <input
            type='text'
            value={this.state.value}
            onChange={this.handleChange}
          />
        </label>
        <input type='submit' value='Submit' />
       </div>
       <div>
       <label>
            Output : 
         {/* I am trying to print the new array here after submitting the form */}
        </label>
        <p>{value}</p>
       </div>
      </form>
    );
  }
}

export default Chase;
Affy
  • 181
  • 1
  • 2
  • 13

1 Answers1

1

Issue

You don't update your state with the correct key value, instead you are adding a new state variable this.state.newVal.

Solution

handleChange = (e) => {
  e.preventDefault()
  let newspoo = e.target.value
  let createArr= newspoo.split(' ')
  let newVal = Array.from(new Set(createArr))
  this.setState(
    { value: newVal }, // <-- use correct state key
    () => {
      console.log(newVal)
    },
  );
};
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Thanks @Drew it worked, also can you explain me does handleSubmit should hold the state or its only to have the prevent default method? – Affy Jan 16 '21 at 04:01
  • 1
    @Zeba Sorry, I don't quite understand what you are asking. We use `event.preventDefault()` on a `form` element's `onSubmit` event so any default form actions are not taken, primarily the navigation/page reload that occurs. Can you clarify what you are asking for me? – Drew Reese Jan 16 '21 at 04:18
  • My apologize for confusing @Drew, I meant this question which I found the answer here https://stackoverflow.com/q/28479239/11737583 – Affy Jan 16 '21 at 17:03