Created
          April 14, 2020 06:05 
        
      - 
      
 - 
        
Save beardlessman/5e75bec9ad49369a438f9b3b7120b9e6 to your computer and use it in GitHub Desktop.  
    Profile Select With Hooks
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | import { Select, Spin } from 'antd'; | |
| import { IProfile } from 'modules/user/types'; | |
| import React, { useState } from 'react'; | |
| import debounce from 'lodash/debounce'; | |
| import uniqWith from 'lodash/uniqWith'; | |
| const { Option } = Select; | |
| interface IResponse { | |
| data: { | |
| data: IProfile[]; | |
| }; | |
| } | |
| interface IProps { | |
| selectedProfile: IProfile; | |
| defaultOptions: IProfile[]; | |
| actionSearch: (value: string) => Promise<IResponse>; | |
| onChange: (value: string) => void; | |
| } | |
| const ProfileSelect = (props: IProps) => { | |
| const defaultOptions = props.defaultOptions; | |
| const [options, setOptions] = useState(defaultOptions); | |
| const [fetching, setFetching] = useState(false); | |
| const fetchProfiles = (query: string): void => { | |
| if (query && query.length !== 0) { | |
| setOptions([]); | |
| setFetching(true); | |
| props.actionSearch(query).then(response => { | |
| setOptions(response.data.data); | |
| setFetching(false); | |
| }); | |
| } else { | |
| setOptions(defaultOptions); | |
| setFetching(false); | |
| } | |
| }; | |
| const fetchOptions = debounce(fetchProfiles, 800); | |
| const handleChange = (value: string): void => props.onChange(value); | |
| const isEqualGuid = (a, b) => a.guid === b.guid; | |
| const renderOptions = uniqWith( | |
| [props.selectedProfile, ...options].filter(o => o), | |
| isEqualGuid, | |
| ); | |
| return ( | |
| <Select | |
| showSearch={true} | |
| notFoundContent={fetching ? <Spin size="small" /> : 'Ничего не найдено'} | |
| filterOption={false} | |
| onSearch={fetchOptions} | |
| onChange={handleChange} | |
| > | |
| {renderOptions && | |
| renderOptions.map(d => ( | |
| <Option key={d.guid} value={d.guid}> | |
| {`${d.surname} ${d.name}`} | |
| </Option> | |
| ))} | |
| </Select> | |
| ); | |
| }; | |
| export default ProfileSelect; | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment