0

Says I have a todo list, after a todo is created I want to save the item into localstorage. How would the reducer look like? Should I do the setItem method in reducer or in the view?

case 'PUBLISH_TODO_PENDING':
            return { ...state, loading: true, todo_published: false, //do I do this? }
        case 'PUBLISH_TODO_FULFILLED':

          return { 
                ...state, 
                loading: false,
                todo_published: true, //do I do this?
                data: {
                    result: {
                         todo: state.data.todo,
                    }
                }
            }

If I want to use setItem in view the I have to do a flag telling the stat of the todo wether is published or not. It's silly I have to put the flag in initial state too.

Jenny Mok
  • 2,744
  • 9
  • 27
  • 58

2 Answers2

4

You should use redux-thunk. In order to use it in your react app, use following snippet in your store.

const configureStore = (initialState) => (
    createStore(
    reducer,
    initialState,
    composeEnhancers(
        applyMiddleware(thunk)
    )
)

Moreover, it is a better practice to write the code involving setting and getting from local storage in a separate folder, say 'utils' and import the same in your action page inside the action.

rmjoia
  • 962
  • 12
  • 21
  • I don't see any localstorage code in above, where does the localstorage util be placed? within createStore's param? – Jenny Mok Oct 19 '17 at 13:09
  • The above code snippet is to enable use of redux-thunks in your actions. You can create the folder 'utils' inside the folder 'src' (assuming you used create-react-app). Inside the the utils folder you can create file containing the all the functionalities involving local storage. – Musfar Saleem Oct 20 '17 at 04:08
  • what is thunk here (the param passed to applyMiddleware. – Jenny Mok Oct 20 '17 at 12:43
0

Saving to localstorage is a Side Effect, which is great to handle using redux-saga so you listen for a particular action and you do your stuff kind of like event listener.