Reputation: 818
I have a search bar on my TODO List:
import React, { Component } from 'react';
import { FilterTasks } from '../../redux/actions/searchbar';
import reducers from '../../redux/reducers';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
class SearchBar extends Component {
render() {
const {search, value} = this.props;
return (
<input
className="form-control"
placeholder = "Filter Tasks"
onChange={(e) => FilterTasks(e.target.value)}
value={value} />
);
}
}
function mapStateToProps({tasks}) {
return {value: tasks.value};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({FilterTasks}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(SearchBar);
Here's my action to filter:
export const SEARCH = 'SEARCH';
export function FilterTasks(value) {
return {type: SEARCH, value};
}
My search bar reducer:
import {SEARCH} from '../actions/searchbar';
const initialState = {}
export default function SEARCHREDUCER(state = initialState, action) {
switch(action.type) {
case SEARCH: {
const {value} = action;
const tasks = state.contents.filter((val) => val.includes(value));
return {...state, value, tasks};
}
default:
return state;
}
}
My Index reducer:
import { combineReducers } from 'redux';
import SEARCHREDUCER from '../reducers/searchbar';
const TaskReducer = (state = [] ,action) => {
switch (action.type){
case 'ADD_TASK':
state = state.concat(action.payload);
break;
case 'DELETE_TASK':
state = state.tasks.filter(task => task !== action.payload)
break;
}
return state;
},
reducers = combineReducers({
tasks : TaskReducer,
SEARCHREDUCER
});
export default reducers;
And my TasksList class where the filtered list should be rendered:
import React, { Component } from 'react';
import {connect} from 'react-redux';
import Task from '../task'
class TaskList extends Component {
render(){
return(
<table>
<thead>
<tr>
<th>Tasks</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{this.props.tasks.map((task,index) => <Task key={index} task={task} />)}
</tbody>
</table>
);
}
}
function MapStateToProps(state){
return{
tasks:state.tasks,
}
}
export default connect (MapStateToProps)(TaskList);
My problem here is that when I type an entry on the search bar the Tasks list does not change at all, It's not showing any kind of error. What i'm missing here?
Upvotes: 2
Views: 2149
Reputation: 11270
FilterTasks(e.target.value)
should be this.props.FilterTasks(e.target.value)
instead, otherwise it'll call the the imported function from actions that is not bound to Redux by your mapDispatchToProps
.
Also, your TaskReducer
and SEARCHREDUCER
are wrong. The reducer
variable is the one with the combined state, not TaskReducer
or SEARCHREDUCER
.
You should just keep the search string in state and do the filtering within TaskList
with this.props.tasks.filter(<insert filter function>).map(<insert map function>)
.
Upvotes: 1