Search code examples
javascriptreactjstypeaheadreact-bootstrap-typeahead

Cannot read property 'paginationOption' of undefined in React Bootstrap Typeahead


In the todos array, it looks for an element withid 4. He writes it to the owner variable. I put the owner variable in thenewArray array. Then, I put newArray inselected = {newArray.slice (0, 1)}. I want to display owner as default in input. I use library: React Bootstrap Typeahead.

Demo: https://stackblitz.com/edit/react-agfvwn?file=index.js

I have error:

Cannot read property 'paginationOption' of undefined

class App extends Component {
  constructor() {
    super();
    this.state = {
      todos: []
    };
  }

  componentDidMount() {
    this.getTodos();
  }

  getTodos = () => {
    axios({
      url: 'https://jsonplaceholder.typicode.com/todos',
      method: "GET"
    })
    .then(res => { 
      this.setState({
        todos: res.data
      });
    })
    .catch(error => {
      console.log(error);
    }) 
  }

  render() {
    console.log(this.state.todos)
    const owner = this.state.todos.find(todo => todo.id === 4)

    const newArray = [];
    newArray.push(owner)

    return (
      <div>
        <Typeahead
          id={'sasas'}
          selected={newArray.slice(0,1)}
          labelKey="title"
          options={this.state.todos}
          ref={(ref) => this._typeahead = ref}
        />
      </div>
    );
  }
}

Solution

  • Your owner is undefined on initial render since getTodos has not yet finished and this.state.todos is empty array.

    You should set your selected item once your data is fetched, for example:

    class App extends Component {
      constructor() {
        super();
        this.state = {
          todos: [],
          selected: []
        };
      }
    
      componentDidMount() {
        this.getTodos().then(() => {
          const todo = this.state.todos.find(todo => todo.id === 4);
          this.setState({
            selected: todo ? [todo] : []
          })
        })
    
      }
    
      getTodos = () => {
        return axios({
          url: 'https://jsonplaceholder.typicode.com/todos',
          method: "GET"
        })
        .then(res => { 
          this.setState({
            todos: res.data
          });
        })
        .catch(error => {
          console.log(error);
        }) 
      }
    
      render() {
        return (
          <div>
            <Typeahead
              id={'sasas'}
              selected={this.state.selected}
              labelKey="title"
              options={this.state.todos}
              ref={(ref) => this._typeahead = ref}
            />
          </div>
        );
      }
    }