I am trying to build a search bar component that will later make an api call and store the results in redux. however I am having trouble getting the onChange method working properly. My text onscreen doesn't change, but I can see in the console that it keeps printing out the initial state plus the last letter I entered. I did some console logs but I can't seem to get my searchReducer to run at all.
// Searchbar.js
const Searchbar = ({ query, results }) => {
const onSubmit = (e) => {
e.preventDefault();
};
const onChange = (e) => {
UpdateQuery(e.target.value);
};
return (
<form onSubmit={onSubmit}>
<label htmlFor="search">Search Bar</label>
<input
className="search-input"
name="search"
type="text"
placeholder="Search Meals..."
value={query}
onChange={onChange}
/>
<input className="search-btn" type="submit" value="Search" />
</form>
);
};
const mapStateToProps = (state) => {
return {
query: state.search.query,
results: state.search.results,
};
};
const mapDispatchToProps = (dispatch) => {
return {
UpdateQuery: (query) => dispatch(UpdateQuery(query)),
UpdateResults: (results) => dispatch(UpdateResults(results)),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Searchbar);
// search-actions.js
import * as actionTypes from "./search-types";
export const UpdateQuery = (query) => {
console.log("query >>> " + query);
return {
type: actionTypes.UPDATE_QUERY,
payload: query,
};
};
export const UpdateResults = (results) => {
console.log("results >>> " + results);
return {
type: actionTypes.UPDATE_RESULTS,
payload: results,
};
};
// search-reducer.js
import * as actionTypes from "./search-types";
const INITIAL_STATE = {
query: "test",
results: ['test'],
};
const searchReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case actionTypes.UPDATE_QUERY:
return {
...state,
query: action.payload,
};
case actionTypes.UPDATE_RESULTS:
return {
...state,
results: action.payload,
};
default:
return state;
}
};
export default searchReducer;
// rootReducer.js
const rootReducer = combineReducers({
shop: shopReducer,
search: searchReducer,
});
export default rootReducer;