.NET-starting-with-js-and-react guy here again :)
I was always struggling with the way how the state should be modified without mutating itself. With the new ES6 spread operator I thought I will not suffer anymore but seems like I am doing something wrong.
I have tried various of approaches how to add the item into the array (code example is from this link )
Reducer:
const patientsInitialState = {
patients : [],
selectedPatient: {}
}
const PatientsReducer = (state = patientsInitialState, action) => {
switch(action.type) {
// other not related cases
case 'ADD_PATIENT':
return {
...state,
patients: [...state.patients, action.payload]
}
// also tried this:
//return {
// patients: [ ...state.patients, action.payload]
//}
default:
return state;
}
}
export default PatientsReducer;
Component:
handleAddPatientClick(patient) {
var config = {
headers: {
'Accept':'',
'Content-Type': 'application/json'
}
};
axios.post(url + 'patients', patient, config).then(res =>
{
this.props.dispatch(addPatientAction(patient));
})
.catch( function(error) {
console.log(JSON.stringify(error, null, 2));
});
}
How I connect my store to props:
@connect((store) => {
return {
patients: store.PatientsReducer.patients
}
})
export default class RegistratePatient extends React.Component {
constructor(props) {
super(props);
this.handleAddPatientClick = this.handleAddPatientClick.bind(this);
// constructor code
}
handleAddPatientClick(patient) {
// code above
}
render() {
// render code
}
}