Tord Larsen
Tord Larsen

Reputation: 2836

How to save the String to the Redux Store

I learn React-Redux and now I need help with the Store. I cannot get this to work I when the action FOUND_BAD_WORD is hit the bad word is in the payload.

I want to update the Redux Store with the word like this: (JAVA style pseudo code)

import { ADD_ARTICLE } from "../constants/action-types";
import { FOUND_BAD_WORD } from "../constants/action-types";

    const initialState = {
      articles: []
    };
    var badword;

    export default function reducer(state = initialState, action) {
      if (action.type === ADD_ARTICLE) {
        return Object.assign({}, state, {
          articles: state.articles.concat(action.payload)
        });
      }

      if (action.type === FOUND_BAD_WORD) {
        // If user type a bad word then save the word in the store

          badword = action.payload;
      }
      return state;
    } 

I know this is an easy question but I have search for this and only find advanced answers

I have an Object connect with the mapStateToProps on the store badword but cant get that to work because I need to change the badword first, I think??

Upvotes: 0

Views: 1016

Answers (1)

Cepe
Cepe

Reputation: 21

Following the way you are doing it, it would be:

      if (action.type === FOUND_BAD_WORD) {
       return Object.assign({}, state, {badword: action.payload})
    } 

But it would be more elegant to handle the reducer actions in a switch statement and to use object spread.

import { ADD_ARTICLE, FOUND_BAD_WORD  } from "../constants/action-types";

    const initialState = {
      articles: [],
    };
const yourReducerName = (state = initialState, action) => {
  switch(action.type) {
    case ADD_ARTICLE : return {
      ...state,
      articles: [...state.articles, action.payload]
      }
    case FOUND_BAD_WORD : return {
      ...state,
      badword: action.payload
      }
    default: return {...state}
   }
}
export default yourReducerName

Upvotes: 2

Related Questions