Send Action Data to the Store

rthefounding

Randy Rivera

Posted on November 30, 2021

Send Action Data to the Store
  • 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());
Enter fullscreen mode Exit fullscreen mode
  • We have a notesReducer() and an addNoteText() action creator defined in the code editor. We first have to finish the body of the addNoteText() function so that it returns an action object with a type propertywith a value ofADD_NOTE. As well as, a text property set to the note data that's passed into the action creator.
  • After that we gotta finish writing the switch statement in the notesReducer(). We need a case that handles the addNoteText) actions. The case should be executed whenever there is an action of type ADD_NOTE and it should return the text property on the incoming action as the new state.

  • 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
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
rthefounding
Randy Rivera

Posted on November 30, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related