Reputation: 183
I'm trying to understand how to filter a list of items with react/redux. I've build this example https://codesandbox.io/s/m3n0x7mqzj
i want when i click on the category the products category_id is equal to category id and then return the products of same id's
action.js :-
export const selectCategory = (data) => {
console.log("You clicked on category: ", data.name);
return {
type: 'CATEGORY_SELECTED',
payload: data
}
};
reducer-category.js
export default function (state = null, action) {
switch (action.type) {
case 'CATEGORY_SELECTED':
return action.payload;
default:
break;
}
return state;
}
category.js:-
import React, { Component } from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {selectCategory} from '../actions/index';
class Category extends Component{
renderList() {
return this.props.Data.categories.map((user) => {
return (
<option
key={user.id}
onClick={() => this.props.selectCategory(user)}
>
{user.name}
</option>
);
});
}
render() {
return (
<select>
{this.renderList()}
</select>
);
}
}
function mapStateToProps(state) {
return {
Data: state.Data
};
}
function matchDispatchToProps(dispatch){
return bindActionCreators({selectCategory: selectCategory}, dispatch);
}
export default connect(mapStateToProps, matchDispatchToProps)(Category);
Upvotes: 0
Views: 1990
Reputation: 973
You should learn lots of thing about redux and react.
Set your all states in redux, not in component's state.
onChange
function should be on select
element, i didn't
understand why you use onClick
on option
elements.
Use componentWillMount()
or componentDidMount()
to fetch data for
first time on component. Use redux actions inside that lifecycle
methods.
Set initial state on your reducer files and change it from actions.
These are my remarks. Hope this can help! Here is the working example for you. Review this.
https://codesandbox.io/s/6wr900jq8r
Upvotes: 1