Conditional API call and send data in react-select

后端 未结 2 742
你的背包
你的背包 2021-01-27 21:36



        
2条回答
  •  故里飘歌
    2021-01-27 22:07

    There are couple of issues:

    this.handlePartsType = this.handlePartsType.bind(this); is redundant. Also constructor does not have closing bracket. Select.Async is not supposed to be used to load options based on external value, it loads options when input changes.

    Below is rewritten example:

    		const partsType = [
    		    {value: 'front_parts', label: 'Part Condition-Front'},
    		    {value: 'left_parts', label: 'Part Condition-Left'},
    		    {value: 'back_parts', label: 'Part Condition-Back'},
    		    {value: 'right_parts', label: 'Part Condition-Right'},
    		    {value: 'top_bottom_parts', label: 'Part Condition-Top/Bottom'},
    		    {value: 'glass', label: 'Glass Condition'},
    		    {value: 'electrical_parts', label: 'Electrical Parts'},
    		    {value: 'non_electrical_parts', label: 'Non-Electrical Parts'}
    		];
        
        // test wrapper for fetch to be removed to talk to backend
        const fetch = () => Promise.resolve({json: () => Promise.resolve([{promptCode: 'test', text: 'Test option'}])})
    
    		const getParts = (partsType) => {
    		    return fetch(
    			  `http://localhost:4000/${partsType}`,
    			  {
    			      method: 'get'
    			  }
    			)
    			  .then(response => {
    			      if(response.status >= 400){
    				  throw new Error("error");
    			      }
    			      return response.json()
    			  })
    			  .then(parts => {
    			      let partsName = [];
    
    
    			      for(let part of parts) {
    				  partsName.push({value: part.promptCode, label: part.text})
    			      }
    
    
    			      return {options: partsName};
    			  })
    			  .catch(err => {
    			      console.log('could not fetch parts');
    			      console.log(err);
    			      return {options: []}
    			  })
    
    		};
    
    		class Assess extends React.Component {
          state = {
    			    partsType:'front_parts'
    			};
    
          handlePartsType = (partsType) => {
            getParts(partsType).then(({options}) =>
              this.setState({partsType, partsOptions: options})
            )
          };
          
          componentDidMount() {
            this.handlePartsType(this.state.partsType);
          }
    
    		render() {
    		    return (
    		    
    ); } } ReactDOM.render(
    , document.getElementById('root') )
    
    
    
    
    
    
    
    
    
    
    
    
    

提交回复
热议问题