- Actions usually come from some user interaction and they tend to carry some data with them which Redux store needs to know.
- Code:
const ADD_NOTE = 'ADD_NOTE'; const notesReducer = (state = 'Initial State', action) => { switch(action.type) { // Change code below this line // Change code above this line default: return state; } }; const addNoteText = (note) => { // Change code below this line // Change code above this line }; const store = Redux.createStore(notesReducer); console.log(store.getState()); store.dispatch(addNoteText('Hello!')); console.log(store.getState());
- We have a
notesReducer()
and anaddNoteText()
action creator defined in the code editor. We first have to finish the body of theaddNoteText()
function so that it returns anaction
object with atype
propertywith a value of
ADD_NOTE. As well as, atext
property set to thenote
data that's passed into the action creator. After that we gotta finish writing the
switch
statement in thenotesReducer()
. We need a case that handles theaddNoteText)
actions. The case should be executed whenever there is an action of typeADD_NOTE
and it should return thetext
property on the incomingaction
as the newstate
.Answer:
const notesReducer = (state = 'Initial State', action) => { switch(action.type) { case ADD_NOTE: return action.text, default: return state; } }; const addNoteText = (note) => { return { type: ADD_NOTE, text: note } }; console.log(store.getState()); // Initial State store.dispatch(addNoteText('Hello!')); // Hello! console.log(store.getState()); // Initial State
Top comments (0)