Reputation: 1655
I am trying to write a todo note app, I have chosen redux to store a list of notes so every time the user adds a new note it will get added to a store. I want the store to be an array so I can after mapStateToProps and map over the store to list the notes.
The problem that I have is that every time I add a new Note it overrides the old one and the store does not keep an array list of all the notes.
My Form:
import React ,{ useState } from "react";
import './AddNoteForm.scss';
import { Button } from 'react-bootstrap';
import { setNoteData } from '../../actions';
import { connect } from 'react-redux';
function AddNoteForm (props) {
const [titleData, setTitleData] = useState('');
const [noteData, setNewNoteData] = useState('');
const { handleClose, setNoteData } = props;
//EDITED
const handleSubmit = (e) => {
e.preventDefault();
setNoteData({title: titleData, note: noteData});
handleClose();
}
return (
<div className="AddNoteForm">
<form onSubmit={handleSubmit} >
<div className="AddNoteForm__title">
<label htmlFor="title">Title</label>
<input type="text" name="title" value={titleData} onChange={(e) => setTitleData(e.target.value) } />
</div>
<div className="AddNoteForm__note">
<label htmlFor="note">Note</label>
<textarea type="text" name="note" value={noteData} onChange={(e) => setNewNoteData(e.target.value)} />
</div>
<Button className="AddNoteForm__button" variant="primary" type="submit">
Add
</Button>
</form>
</div>
);
}
const mapDispatchToProps = () => {
return {
setNoteData,
}
}
export default connect(null, mapDispatchToProps())(AddNoteForm);
My Action:
export const SET_NOTE = 'SET_NOTE';
export const GET_NOTES = 'GET_NOTES';
export function setNoteData (note) {
debugger;
return {
type: SET_NOTE,
note
}
}
//EDITED
my Reducer:
import { SET_NOTE } from '../actions';
const setNoteReducer = (state=[], action) => {
switch (action.type) {
case SET_NOTE:
return state.concat([action.note]);
default:
return state
}
}
export default setNoteReducer;Redux console tracking:
As you can see I have called the SET_NOTE action twice which is triggered in my form in 'handleSubmit' but the previous state gets overridden by the new state they don't persist. Also, I am new to react Hooks and not sure I am using it correctly but when I debug it seems it does the job.
Upvotes: 0
Views: 1638
Reputation: 813
Modify switch like following
switch (action.type) {
case SET_NOTE:
let new_state = state.push(action.note)
return Object.assign(state, newState)
default:
return state
}
Upvotes: 0
Reputation: 2028
function noteReducer(state, action){
switch(action.type){
case "SET_NOTE":
return state.concat([action.note]);
default:
return state;
}
}
Upvotes: 1