Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwrite entire state in redux

Tags:

This is yet another novice question about redux. In my app, i would like to be able to load the state from a text file, i.e. to be able to completely re-initialise the whole state object. So I don't want to reset the state to an initial value, but replace it with a new one. (FYI the application stores data merely in the browser's localStorage. Also, so far I have followed the awesome tutorial from http://redux.js.org/docs/introduction/index.html) I have tried several approaches, but none of them have yielded results. For example, in my reducers/index.js i have:

export default function App (state = {}, action) {
  return {
    todos: todos(state.todos, action),
    ...
    global: global(state, action)
  }
}

In reducers/global.js I have:

const global = (state = {}, action) => {
  switch(action.type) {
    case 'LOAD_DB_FROM_FILE':
      return action.fileContents;
    default:
      return state
  }
}

What happens is that the state object, oddly (or not :)) enough, gets a new field called global which contains the original state (and not the one read from the file) and it even gets nested for a couple of levels (so i have a replica of the state at state.global.global.)

I am aware of the hackiness of this approach, even willing to accept a fundamental flaw (due to my ignorance) in my setup, still i haven't been able to find a simple and unambiguous answer to my problem.

As always, any help would be much appreciated.

like image 242
Dimitar Roszenov Ruszev Avatar asked Jun 11 '16 13:06

Dimitar Roszenov Ruszev


People also ask

Can we change Redux state directly?

Redux restricts updating the state to this method only. This strict way of updating the state ensures that the state can not be changed directly either by view or any network callback. The only way to update a state is by defining the action and then dispatching it. Remember that actions are plain JavaScript objects.

Should I put all state in Redux?

Some users prefer to keep every single piece of data in Redux, to maintain a fully serializable and controlled version of their application at all times. Others prefer to keep non-critical or UI state, such as “is this dropdown currently open”, inside a component's internal state. Using local component state is fine.


1 Answers

I know little about redux, but based on what I know about JavaScript I would say you need something like this:

// reducers/index.js

export default function App (state = {}, action) {
  state = global(state, action);
  return {
    todos: todos(state.todos, action),
    ...
  };
}

So the reducer named global has a chance to replace the whole state object at once.

like image 188
Tamas Hegedus Avatar answered Sep 30 '22 19:09

Tamas Hegedus