Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create array from state value and setstate after removing duplicates in reactjs

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;
like image 957
Affy Avatar asked Feb 11 '26 11:02

Affy


1 Answers

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)
    },
  );
};
like image 137
Drew Reese Avatar answered Feb 13 '26 08:02

Drew Reese