Kamran Nazir
Kamran Nazir

Reputation: 692

Dispatch an action onChange input

I'm trying to dispatch an action on input onChange. The searchQuery() get's called but doesn't dispatch the action.

Here is the component with the input tag

const SearchBar = () => 
  <Card>
    <div className={styles.searchFieldContainer}>
      <div className={styles.field}>
        <input type="text" onChange={(event)=> searchQuery(event.target.value)} placeholder="Search for items or sellers" />
      </div>
      <Button className={styles.searchButton}>
        Search
      </Button>
    </div>
  </Card>

const mapStateToProps = () => {
  return {

  }
} 

const mapDispatchToProps = (dispatch) => {
  return {
    dispatch
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(SearchBar);

The searchQueryRequest() request does not get dispatched. The searchQuery() function works though.

export const SEARCH_QUERY_REQUEST = 'SEARCH_QUERY_REQUEST'
function searchQueryRequest(query) {
  console.log(query) // doesn't get called
  return { type: SEARCH_QUERY_REQUEST, query }
}

export function searchQuery(query) {
  console.log(query) // works till here
  return (dispatch, getState) => {
    dispatch(searchQueryRequest(query))
  }
}

Upvotes: 1

Views: 3013

Answers (1)

Don Carlos
Don Carlos

Reputation: 26

You have to dispatch the searchQuery() function as well.

const SearchBar = ({ searchQuery }) => 
  <Card>
    <div className={styles.searchFieldContainer}>
      <div className={styles.field}>
        <input type="text" onChange={(event)=> searchQuery(event.target.value)} placeholder="Search for items or sellers" />
      </div>
      <Button className={styles.searchButton}>
        Search
      </Button>
    </div>
  </Card>

const mapStateToProps = () => {
  return {

  }
} 

const mapDispatchToProps = (dispatch) => {
  return {
    searchQuery: (val) => dispatch(searchQuery(val))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(SearchBar);

Upvotes: 1

Related Questions