Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Redux: How to share data between reducers?

I have a basic todo list. The todo input field for the todo list has an onChange event that triggers an action and sends event.target.value to a reducer and stores each character the users types to a property of the store object.

When the user submits the form I want to get the data that was previously stored via the onChange event, then I want to place it on a new property on the store object.

How do I get data that was previously entered from the store and pull it into a different reducer?

In all the examples I've seen, reducers start with an "initial state". I don't want that, I want the previous state that the user entered.

Below is a CodeSandbox version of the code (for some reason the orange-beige tab to the right needs to be switch to the left to blue for it to render the form. If you don't do that it won't work).

https://codesandbox.io/s/pwqlmp357j

like image 777
William Avatar asked Sep 06 '25 09:09

William


1 Answers

Ask yourself whether you've structured your reducers correctly. If a and b are not independent of one another, why are they separate reducers?

Well if we talk about correctly structuring the reducer, cachedInput and todoList should live in single reducer. There is no need to create another reducer. Also I guess you need to grab the input value all at once(when user clicks on submit) and send it to store.

If still you want to create seperate reducers then you can follow the approach given below :

Answer to How to access or share data already in store, inside the reducers?

Don't use combineReducers.

Example

replace this code

export const a = combineReducers({
  cachInput,
  newTodo
});

with

export default (state = {}, action) => {
  return {
    cachInput: cachInput(state.app, action, state),
    newTodo: newTodo(state.posts, action, state),
  };
};

reducer would be like

const reducer = (state = initialState, action, root) => {....}

and you can access the previous state from root

like image 197
Shivam Avatar answered Sep 09 '25 03:09

Shivam