Reputation: 2695
I am new to react js. Here, I do have a functionality where there are three diff rows that can be added or removed. I have a reducer which is like,
const initialState = {
Low: [
{
id: 'L0',
technologyId: 0,
technology: '',
type: '',
count: '',
level: 'EASY'
}
],
Medium: [
{
id: 'M0',
technologyId: 0,
technology: '',
type: '',
count: '',
level: 'Medium'
}
],
High: [
{
id: 'H0',
technologyId: 0,
technology: '',
type: '',
count: '',
level: 'Tough'
}
],
SO, Here, I want to have this as a generic,so, I am trying to add objects on click of the plus and remove on - . So,
Here, I am adding using ,
const tempObj = {
id: tempvar + id,
technologyId: 0,
technology: temp[0].technology,
type: type,
count: '',
level: addtype
}
I create this object now depend upon the addType I add it in that particular array.
I do it using this way,
const addData = [...this.props.lowData[addtype], tempObj];
this.props.addNewTech(addData);
So, Here this ...this.props.lowData[addtype]
returns an object not an array, is this the problem ? If yes, It should return an array not the object but how is this returning the object and not an array.
My props.lowData is like ,
an object with three different arrays, I mean same as that of the reducer .,But every time I add it adds that element in the Low
array only and not in the medium or high. Can any one help me with this ?
Upvotes: 1
Views: 184
Reputation: 3131
The problem is in the reducer you are only updating the Low
property. You need to check what property needs to update. For that you can pass addtype
to your action creator like so
this.props.addNewTech({ addData, addtype });
And then in action creator
export function addNewTech(data) {
return {
type: ADD_NEW,
data //is equavalent to data: data (ES6)
}
}
And then in reducer dynamically update the object
case ADD_NEW:
return {
...state,
//here choose the property to be updated dynamically
//replace Low: action.data with below line
[action.data.addtype]: action.data.addData,
error: false,
}
**Note here [action.data.addtype]: action.data.addData
we are using computed property names in ES6.
Upvotes: 1