0

trying my hand on redux as a new react developer. i want to dispatch an action passing it a string that will update the text property as a new state.

Here is how i have done it.

const notesReducer = (state = 'Initial State', action) => {
 switch(action.type) {
   case "ADD_NOTE":
    return({
     text: action.text
    })
  default:
    return state;
 }
};

const addNoteText = (note) => {
  return ({
   type: "ADD_NOTE",
   text: note
   })
 };
 const store = Redux.createStore(notesReducer);
 console.log(store.getState());
 store.dispatch(addNoteText('Hello!'));
 console.log(store.getState());

The action creator addNoteText() takes in an argument to pass to the text property. please help

yrufai
  • 61
  • 2
  • 11

2 Answers2

3

Here is my solution to this challenge, only thing you really have to change from what you have is what you return in the switch statement:

 const ADD_NOTE = 'ADD_NOTE';

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
}

};

const store = Redux.createStore(notesReducer);

console.log(store.getState());
store.dispatch(addNoteText('Hello!'));
console.log(store.getState());
0
const notesReducer = (state = {
  text: ''
}, action) => {
  switch(action.type) {
    case "ADD_NOTE": {
      return Object.assign({}, state, { text: action.text })
    }
    default:
      return state;
  }
 };

 const addNoteText = (note) => {
  return(
    {
      type: "ADD_NOTE",
      text: note
    }
  )
  };

  const store = Redux.createStore(notesReducer);
  console.log(store.getState());
  store.dispatch(addNoteText('Hello!'));
  console.log(store.getState());
AlbertS
  • 706
  • 5
  • 12
  • that would have work if i had the object spread operator setup. This is on freecodecamp.org and i have to figure a way to handle this without using the spread opereator – yrufai Nov 18 '18 at 12:15
  • see updated code above. The alternative way is Object.assign(). See https://stackoverflow.com/questions/32925460/object-spread-vs-object-assign – AlbertS Nov 18 '18 at 16:34
  • to use es6 you can add babel to your html file. See https://stackoverflow.com/questions/43931538/how-to-load-es6-react-babel-code-in-html-with-cdn – AlbertS Nov 18 '18 at 16:38