Reputation: 77
I'm trying to implement search, and I did the action for input which works every time when I enter text to search input, but the reducer does not trigger and I can't understand why, and the strangest thing, that another actions and reducers work as it should, and only one doesn't.
search component
import React, {Component} from 'react'
import './search.css';
import axios from 'axios'
import {getPlayList,setSearchValue} from "./actions";
import {connect} from "react-redux";
class Search extends Component {
state = {
query: '',
results: []
};
getInfo = () => {
this.props.getPlayList(this.state.query);
console.log(this.props.search.searchPlayList);
};
handleInputChange = () => {
/*this.setState({
query: this.search.value
}, () => {
if (this.state.query && this.state.query.length > 1) {
this.getInfo();
}
});*/
setSearchValue(this.search.value);
console.log(this.props.search.searchValue);
};
render() {
return (
<form>
<input
placeholder="Search for..."
ref={input => this.search = input}
onChange={this.handleInputChange}
/>
</form>
)
}
}
const mapStateToProps = store => {
return {
search: store.search
};
};
export default connect(mapStateToProps, {getPlayList,setSearchValue})(Search);
Action methods:
export const getPlayList = (queryParam) => {
return function (dispatch) {
dispatch({type: FETCH_PLAYLIST_REQUEST});
axios.get(`https://cors-anywhere.herokuapp.com/https://api.deezer.com/search/track?q=${queryParam}`).then(response => {
dispatch({
type: FETCH_PLAYLIST_SUCCESS,
payload: {
playlist: response.data.data,
currentTrack: response.data.data[0]
}
});
}).catch(err => {
dispatch({
type: FETCH_PLAYLIST_FAILURE,
payload: err,
});
})
}
};
export const setSearchValue = (value) => {
console.log('setSearchValue',value);
return function (dispatch) {
dispatch({
type: FETCH_SEARCH_VALUE,
payload: value,
});
}
}
Reducer
import {
FETCH_PLAYLIST_FAILURE,
FETCH_PLAYLIST_REQUEST,
FETCH_PLAYLIST_SUCCESS,
FETCH_SEARCH_VALUE
} from "../actions/types";
const initialState = {
searchPlayList:null,
currentTrack:null,
searchValue:null,
index: 0,
isLoading: false,
};
export default function (state = initialState, action) {
switch (action.type) {
case FETCH_PLAYLIST_REQUEST:
return {
...state,
isLoading: true
};
case FETCH_PLAYLIST_SUCCESS:
return {
...state,
searchPlayList: action.payload.playlist,
errors: null,
isLoading: false,
};
case FETCH_PLAYLIST_FAILURE:
return {
...state,
errors: action.payload
};
case FETCH_SEARCH_VALUE:
console.log('action.payload',action.payload);
return {
...state,
searchValue: action.payload
};
default:
return state
}
}
Upvotes: 0
Views: 648
Reputation: 23064
You have to change this line:
setSearchValue(this.search.value);
To this:
this.props.setSearchValue(this.search.value);
The setSearchValue
in props will dispatch the action to the store. Just calling setSearchValue
by itself doesn't do anything, since it has not been connected to redux.
Upvotes: 3