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;

1 Answer 1

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)
    },
  );
};
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @Drew it worked, also can you explain me does handleSubmit should hold the state or its only to have the prevent default method?
@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?
My apologize for confusing @Drew, I meant this question which I found the answer here stackoverflow.com/q/28479239/11737583

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.