- 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 anactionobject with atypepropertywith a value ofADD_NOTE. As well as, atextproperty set to thenotedata that's passed into the action creator. After that we gotta finish writing the
switchstatement in thenotesReducer(). We need a case that handles theaddNoteText)actions. The case should be executed whenever there is an action of typeADD_NOTEand it should return thetextproperty on the incomingactionas 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)