dennismonsewicz
dennismonsewicz

Reputation: 25542

Issues updating state in redux reducer

I have the following dispatched action:

export function fetchUsersForTeam() {
    return {
        type: 'FETCH_USERS_FOR_TEAM__RESOLVED',
        teamId: 123,
        responseData: [
            { userId: 1, name: 'Alice' },
            { userId: 2, name: 'Bob' },
            { userId: 3, name: 'Chris' }, // This is new! "Christopher" is now "Chris"
        ],
    };
};

Here is my reducer:

import _ from 'lodash';

function getUserById(users, id) {
    return _.find(users, {userId: id});
}

const userServiceReducer = (state, action) => {
    if (action.type === 'FETCH_USERS_FOR_TEAM__RESOLVED') {
        const userIds = state.usersForTeams[action.teamId];
        const data = action.userData;
        const result = userIds.map(idx => ({
            ...getUserById(state.userData, idx),
            userData: getUserById(action.responseData, idx),
        }));
        console.log(result);

        return result;
    }

    return state;
};

export default userServiceReducer;

Here is the initial state:

const initState = {
    userData: {
        1: { userId: 1, name: 'Alice' },
        3: { userId: 3, name: 'Christopher' },
        4: { userId: 4, name: 'Dave' },
        5: { userId: 5, name: 'Eliza' },
    },
    usersForTeams: {
        123: [1, 3],
        456: [3, 4, 5],
    },
};

The new state, after the reducer has done its' thing, should look like the following:

const newState = {
    userData: {
        1: { userId: 1, name: 'Alice' },
        3: { userId: 3, name: 'Chris' },
        4: { userId: 4, name: 'Dave' },
        5: { userId: 5, name: 'Eliza' },
    },
    usersForTeams: {
        123: [1, 3],
        456: [3, 4, 5],
    },
};

Every time the reducer runs, the return result is an array of objects where each id matches a userId from the matched key in the usersForTeams.

In the above example, my output is:

[{ userId: 1, name: 'Alice' },
{ userId: 3, name: 'Christopher' },]

Upvotes: 1

Views: 50

Answers (1)

Nantaphop
Nantaphop

Reputation: 564

Your mistake is you did not merge your new userData to the old state. Try something like this.

function getUserById(users, id) {
    return _.find(users, user => user.userId === id);
}

const userServiceReducer = (state, action) => {
    if (action.type === 'FETCH_USERS_FOR_TEAM__RESOLVED') {
        const userIds = state.usersForTeams[action.teamId];
        const data = action.userData;
        const newUserData = userIds.map(idx => ({
            ...getUserById(state.userData, idx),
            userData: getUserById(action.responseData, idx),
        }));

        return _.merge({}, state, {userData: newUserData});
    }

    return state;
};

Upvotes: 1

Related Questions