Reputation: 2876
I'm displaying a list of items from my state store. I want to update this list with an onClick Button. My list is displayed with a map function, at first it works well however but I'm clicking the button I've got the following error data.map is not a function
. When I running my component without displaying the data list item, everything works fine, state update correctly.
Here is my reducer with my list of Items :
var all = [
{x: 'a', y: 20},
{x: 'b', y: 14},
{x: 'c', y: 12},
{x: 'd', y: 19},
{x: 'e', y: 18},
{x: 'f', y: 15},
{x: 'g', y: 10},
{x: 'h', y: 14}
];
var filtered = [
{x: 'a', y: 9},
{x: 'b', y: 5},
{x: 'c', y: 6},
{x: 'd', y: 12},
{x: 'e', y: 10},
];
const ChartData = (state = all, action) => {
switch (action.type) {
case 'DATA_CHART_ALL':
return { all: update(state.all, {$set: all})}
case 'DATA_CHART_FILTER':
return { all: update(state.filtered, {$set: filtered})}
default:
return state;
}
};
and here is my component :
function DisplayData ({ data, DataSetUpdate }) {
return (
<div>
<ul>
{ data.map((m, i) =>
<li key={i}>{m.x} - {m.y}</li>
)}
</ul>
<button onClick={DataSetUpdate}>dataSetupdate</button>
</div>
);
}
const mapStateToProps = (state) => {
return {
data: state.ChartData
};
};
const mapDispachToProps = (dispatch) => {
return {
DataSetUpdate: () => {dispatch (datachartFilter())},
};
};
I guess there is something wrong in my component. I think I need to use something like this.props somewhere but I don't know where. I've also try to build a ES6 component class DisplayData extends React.Component
with a constructor method but with this I don't know how to pass my DataSetUpdate function.
here is the JS bin https://jsbin.com/xocopal/edit?js,console,output
Thanks !
Edit#1 : My JS bin doesn't work because I can't make the immutable libraries works : https://cdnjs.com/libraries/immutable so the update method in my reducer is undefined.
Upvotes: 1
Views: 1253
Reputation: 1296
reducers should just changes the state based on input (always a new state) if you ever hookup to an API, you would do the calls in your actions and then send the data to your reducer for the update
I think you just need to update your reducer to This makes a simpler and cleaner solution
const ChartData = (state = all, action) => {
switch (action.type) {
case 'DATA_CHART_ALL':
return action.data
case 'DATA_CHART_FILTER':
return action.data
default:
return state;
}
};
and your action to
function datachartAll() {
return {
type: 'DATA_CHART_ALL',
data: all
};
}
function datachartFilter() {
return {
type: 'DATA_CHART_FILTER',
data: filtered
};
}
see https://jsbin.com/vobuduluni/1/edit?js,console,output
Upvotes: 2