Search code examples
javascriptreactjsonchangehl7-fhir

React-Select onChange to store a value to pass to API call


I'm working on my first ever web-app and bootstrapped this app, I'm having trouble changing the URL of an API get request. I'm using react-select to create a dropdown menu, and I want the dropdown selection to alter search criteria, for example:

I have a baseurl.com/

and want to create a variable based off the dropdown selection, to append to the baseurl. My two options from the dropdown are 'Name' and 'Birthday', and if you select 'Name', the URL would be baseurl.com/Patient?name= + inputvalue.

and if you select 'birthday', the URL will be baseurl.com/Patient?birthdate=eq + inputvalue

I want to keep the baseURL as is because I will have to add more options to the select eventually. I've already got the inputvalue working in my app so I don't need to make changes to it I believe.

Here is some of my code so far, which gives me a "Cannot read property 'value' of undefined" error" when I make a selection. Also I haven't yet made the component to store the state as a variable, but I'll cross the bridge when it comes to it 😅 Any insight is appreciated, thanks :

const choice = [
  {value : "Name", label: "Name" },
  {value : "bDay", label: "Birthday (YYYY-MM-DD)"} 
];    


class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      inputValue: 'Search',
      queryResult: {},
      criteria: '',
      showSVG: false
    };
    this.handleChange = this.handleChange.bind(this);
    this.getInputValue = this.getInputValue.bind(this);
    this.baseURL = this.baseURL.bind(this);
  }


  getInputValue(e) {
    this.setState({ inputValue: e.target.value });
  }

  handleChange(e) {
  this.setState({criteria: e.target.value});
  console.log(e.target.value);
  }

  baseURL(e) {
    const url = 'https://baseURL.com/';


[BLOCK FOR FETCH REQUEST]

render() {

    
    return (
      <div className="input-wrapper">
        {/* ON CHANGE SELECT */}
            <Select options={choice} value={this.state.criteria} onChange={this.handleChange} />
              
        <input
          type="text"
          value= {this.state.inputValue}
          onFocus = {() => this.setState({ inputValue: '' })}
          onChange={this.getInputValue}
          onKeyDown={this.baseURL}  />
       <img className={this.state.showSVG ? "isVisable" : ""} src="assets/icons/grid.svg" />  
        { Object.keys(this.state.queryResult).length !== 0 ? <PatientInfoBlock data={this.state.queryResult} /> : null }
        { !this.state.queryResult ? <h3>Sorry no results match ''{this.state.inputValue}''</h3> : null }
      </div>
    );
  }

'''

Solution

  • handleChange should be:

    handleChange(selectedOption) {
      this.setState({criteria: selectedOption});
    }
    

    selectedOption type is:

    {
     value: string,
     label: string
    }