CatMouse2020
CatMouse2020

Reputation: 99

Using react-select I've got next issue: Cannot read property 'value' of undefined

I'm using react-select. When I'm selecting a determinate value from select I've got the next issue

TypeError: Cannot read property 'value' of undefined

Also, values fetched from reducer todoList are not showed, I can't see them.

This is my code:

import Select from "react-select";
import "./styles.css";
import { searchTodos } from "../../actions/ServiceActions";

class SelectedTodo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedTodo: ""
    };
    this.handleChange = this.handleChange.bind(this);
  }
  bringTodos = () => {
    //WHEN I'M EXECUTING THESE CODE LINES I CAN'T SEE TODOS VALUES
    return this.props.todoList.map(todo => {
      return (
        <option key={todo._id} value={todo._id}>
          {todo.name}
        </option>
      );
    });
  };

  handleChange = e => {
    this.setState({ selectedTodo: e.target.value });
  };

  componentDidMount() {
    this.props.searchTodos();
  }

  render() {
    const { loading } = this.props;

    if (loading) {
      return <span>...Loading</span>;
    }
    return (
      <Select
        className="form-container"
        classNamePrefix="react-select"
        placeholder="Please, insert a todo"
        value={this.state.selectedTodo}
        onChange={this.handleChange}
        options={this.bringTodos()}
      />
    );
  }
}

function mapState(state) {
  return {
    todoList: state.todosDs.todoList
  };
}
const actions = {
  searchTodos
};
SelectedTodo = connect(
  mapState,
  actions
)(SelectedTodo);

export default SelectedTodo;

The expected behavior is dropdown shows todos and when I'm selecting a todo value I'm not getting error

TypeError: Cannot read property 'value' of undefined

Upvotes: 0

Views: 11705

Answers (2)

Zunaib Imtiaz
Zunaib Imtiaz

Reputation: 3119

The package react-select directly returns the json that has the value like

{label:"ABC", value:"abc"}

Change this

  handleChange = (e) =>{
  this.setState({selectedTodo: e.target.value});
  }

To this

handleChange = (e) =>{
  this.setState({selectedTodo: e});
  }

Upvotes: 9

sourav satyam
sourav satyam

Reputation: 986

I think as the documentation of react-select says

 <Select
    value={selectedOption}
    onChange={this.handleChange}
    options={options}
  />

this.handleChange will directly return the selected option rather then event object.

    handleChange = selectedOption => {
    this.setState({ selectedOption });
    console.log(`Option selected:`, selectedOption);
  };

and I think you don't need to bind the handleChange method as well.

Upvotes: 1

Related Questions