Redux managing a string always returns "undefined"

Viewed 116

I have a search box, in which when I type something I trigger onChange, and in onChange I call my redux function which should set the "showSearchQuery" in redux store to the string that is passed, but instead I always get "undefined". Can anyone help?

Here are the components/redux code in question:

search box component:

import React from 'react';
import './search-box.styles.css';
import { connect } from 'react-redux';
import { setShowSearchQuery } from '../../redux/actions/index';

class SearchBox extends React.Component {
  constructor() {
    super();

    this.state = {
      searchQuery: '',
    };
  }

  handleChange = (event) => {
    // console.log('EVENT TARGET VAL', event.target.value);
    this.setState({ searchQuery: event.target.value });
    let query = this.state.searchQuery;
    setShowSearchQuery(query);
  };

  render() {
    return (
      <input
        type='search'
        placeholder={'Search by title'}
        onChange={this.handleChange}
      />
    );
  }
}

const mapStateToProps = (state) => {
  return {
    showSearchQuery: state.showSearchQuery,
    loading: state.loading,
  };
};

export default connect(mapStateToProps, { setShowSearchQuery })(SearchBox);

action:

export const setShowSearchQuery = (data) => {
  return {
    type: SET_SHOW_SEARCH_QUERY_SUCCESS,
    data,
  };
};

reducer:

import { setShowSearchQueryUtil } from './shows.utils';


 case SET_SHOW_SEARCH_QUERY_SUCCESS:
      return {
        ...state,
        showSearchQuery: setShowSearchQueryUtil(action.data),
        loading: false,
      };

utils function:

export const setShowSearchQueryUtil = (query) => {
  return query;
};

Now whereever I try to access "showSearchQuery" I always get undefined.

2 Answers

Your Import statement is correct

import { setShowSearchQuery } from '../../redux/actions/index';

In handleChange:

handleChange = (event) => {
    // console.log('EVENT TARGET VAL', event.target.value);
    this.setState({ searchQuery: event.target.value });
    let query = this.state.searchQuery;
    this.props.setShowSearchQuery(query);
  };

and

const mapDispatchToProps = dispatch => {
    return {
        setShowSearchQuery: data => {
            dispatch(setShowSearchQuery(data));
        }
    };
};

const mapStateToProps = (state) => {
  return {
    showSearchQuery: state.showSearchQuery,
    loading: state.loading,
  };
};

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

setShowSearchQuery should come from props hence it should be this.props. setShowSearchQuery(query) inside handleChange event.

handleChange = (event) => {
    // console.log('EVENT TARGET VAL', event.target.value);
    this.setState({ searchQuery: event.target.value });
    let query = this.state.searchQuery;
    this.props.setShowSearchQuery(query);
  };
Related