Bromox
Bromox

Reputation: 687

Redux updating state in another reducer

Setup

In my app I have students who are assigned homework. Each time a student is created I loop through current homework and update homework array for each student.

My issue is when I create a homework. Not only does that homework have to be created, but I then need to assign it to specific students once its created.

I have split my application into three reducers; classes, students, and homework.

Question

How can I update my students state from the Homework reducer? I need to wait until the homework is created and then assign the homework array in each student. Perhaps I can dispatch one action and then another?

case actionTypes.CREATEHOMEWORKS:
    // Get new homework description
    const newHomework = action.newHomework
    // Get the currently active class
    const activeClass = action.activeClass.key;
    // Get users current browser data
    const dateCreated = getCurrentDate();
    // Generare a new UID
    const key = guid();
    // Create a new homework object
    const homework = { key: key, class: activeClass, dateCreated: dateCreated, description: newHomework };
    // Get the current homework array
    const homeworks = JSON.parse(JSON.stringify(state.homeworks));
    // Combine current homework with new homework object.
    homeworks.push(homework);
    
    // I now need to update students to have this homework but they are handled
    // in another state

enter image description here

Upvotes: 5

Views: 2366

Answers (1)

Anthony
Anthony

Reputation: 6482

Your reducer should be a pure function - that is, given the same input, it will always generate the same output. You are generating a random GUID in your reducer, so the same input will never give the same output. If you were to move the GUID generation to your action, you could pass it in the payload of your CREATEHOMEWORK action, and then also dispatch it in a ASSIGNHOMEWORK action that your students reducer handles.

Upvotes: 1

Related Questions