Umbro
Umbro

Reputation: 2204

The function has several arguments. However, do not pass all parameters

From select I choose the value completed,uncompleted or inprogress. In the handleStatus function, I call thegetDetail function and passes it the value status = e.target.value. However, in the getDetail function inconsole.log (status)return meundefined

Code here: https://stackblitz.com/edit/react-kk4yv8

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';

class App extends Component {

  constructor (props) {
    super(props);
    this.state = {
      items: [],
      status: ''
    }
  }

    handleStatus = (e) => {
        this.setState({
                status: e.target.value
        })

        this.getDetail(status = e.target.value)
    }

    getDetail = (query, status) => {
        console.log(status)
    }

  render () {
    return (
      <div>
        <select
            value={this.state.status}
            onChange={(e) => this.handleStatus(e)}
        >
            <option value="completed">completed</option>
            <option value="uncompleted">uncompleted</option>
            <option value="inprogress">inprogress</option>
        </select>   
      </div>
    )
  }
}

render(<App />, document.getElementById('root'));

Upvotes: 0

Views: 46

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85132

this.getDetail(status = e.target.value)

javascript does not have named arguments. This code means "assign e.target.value to the variable status, and then pass that in as the first parameter. Inside of getDetail, that first parameter is assigned to the local variable query. No second parameter was passed in, so inside getDetail, the second parameter is undefined. That second parameter may be referred to as status locally, but this is unrelated to what's going on outside the function.

If you want to pass e.target.value in as the status, you need to put it as the second parameter:

this.getDetail(undefined, e.target.value);

For this reason, it's common to put variables that are optional towards the end of the argument list, so you can simply omit them, rather then filling in an explicit undefined.

Another option if you have a large set of arguments to pass in is to use a single argument, which is an object. The code inside the function can check if properties exist on that object, and code calling the function can omit or include properties on the object at will. For example:

const example = (options) {
  if (options.status) {
    // whatever
  }
  if (options.query) {
    // whatever
  }
}

// To be used like:

example({ query: 'foo', status: 'complete' });
example({ status: 'incomplete' });
example({ query: 'bar' });

Upvotes: 6

Related Questions