Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async React-select with redux

I am trying to make an async react-select component with redux but somehow not able to get search results in the dropdown. Very new to this. Please help :)

import React, { PropTypes } from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import Select from 'react-select';

import { fetchInstitutionsIfNeeded } from '../../actions/institutions';

class Signup extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: null
        };
        this.getInstitutions = this.getInstitutions.bind(this);
        this.onChange = this.onChange.bind(this);
    }

    onChange(input) {
        this.setState({
            value: input
        });
    }

    getInstitutions(input) {
        const { dispatch } = this.props;
        if (!input) {
            return Promise.resolve({ options: [] });
        }
        dispatch(fetchInstitutionsIfNeeded(input));
    }

    render() {
        let options = this.props.options;
        return (
            <div>
                <Select.Async
                    name="institute"
                    value={this.state.value}
                    autoload={false}
                    onChange={this.onChange}
                    loadOptions={this.getInstitutions}
                />
            </div>
        );
    }
}

const mapStateToProps = (state) => ({
    options: state.institutions.options
});

export default connect(mapStateToProps)(Signup);

Also options object is also properly formatted and is getting updated properly in redux store but not reflecting back in select async's dropdown.

like image 943
user2771402 Avatar asked May 22 '17 09:05

user2771402


1 Answers

Try this, we can also return from action but it breaks the whole idea of reducers.

// actions.js
export const getProducts = (input = '') => async (dispatch) => {
  dispatch({
    type: GET_PRODUCTS_PENDING,
    payload: {},
  });
  try {
    const response = await axios.get(`/api/v1/products/`);
    dispatch({
      type: GET_PRODUCTS_SUCCESS,
      payload: response.data,
    });
  } catch (error) {
    // handle errors
  }
};

// components.jsx
class Signup extends PureComponent {
  async getProductsForSelect(input) {
    await this.props.getProducts(input);
    return this.props.product.options;
  }

  render() {
    const { handleSubmit } = this.props;
    return (
      <form onSubmit={handleSubmit}>

        <AsyncSelect
          isMulti
          cacheOptions
          defaultOptions
          loadOptions={(e) => this.getProductsForSelect(e)}
        />

      </form>
    );
  }
}
like image 75
Artem Bernatskyi Avatar answered Sep 20 '22 10:09

Artem Bernatskyi