Reputation: 71
When I wrote my search function in the state of my component I got the results I expected. For example, I queried the google books api and I made a search for Halo. I got what I expect like Halo: Fall of Reach, Halo: The Flood ... etc.
But when I moved the search function into Redux, no matter what I search I get the same incorrect data returned. How does this happen?
So this is my action in redux
export const searchedBooks = search => async dispatch => {
const url = `https://www.googleapis.com/books/v1/volumes?q=${search}&orderBy=relevance&maxResults=30&key=API_KEY`;
try {
const res = await axios.get(url, {
transformRequest: [
(data, headers) => {
delete headers["access-token"];
delete headers["uid"];
delete headers["client"];
delete headers["expiry"];
delete headers["token-type"];
delete headers.common;
return data;
}
]
});
dispatch({
type: SEARCH_BOOKS,
payload: res.data
});
} catch (error) {
dispatch({
type: GET_ERRORS,
payload: error.response.data
});
}
};
Before I put this in my actions I tested it in React. It's pretty much the same code I used. I believe the error is coming from ${search} I don't know if template literals work the same in Redux.
Component where I do my search
class Search extends Component {
state = {
search: "",
books: []
};
componentWillReceiveProps(nextProps) {
if (nextProps.errors) {
this.setState({ errors: nextProps.errors });
}
}
searchBooks = e => {
e.preventDefault();
this.props.searchedBooks();
};
onChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
render() {
console.log(this.props.books);
return (
<div>
<h1>hi from search</h1>
<form>
<input
onChange={this.onChange}
type="text"
name="search"
placeholder="Title or Author(s)"
value={this.state.search}
/>
<button onClick={this.searchBooks}>Search</button>
</form>
</div>
);
}
}
const mapStateToProps = state => ({
books: state.books
});
export default connect(
mapStateToProps,
{ searchedBooks }
)(Search);
Upvotes: 0
Views: 48
Reputation: 5302
You're not actually passing a parameter to this.props.searchedBooks
. Presumably you want the value from your input, so just update searchBooks
to:
searchBooks = e => {
e.preventDefault();
this.props.searchedBooks(this.state.search);
};
Upvotes: 2