Laylaz
Laylaz

Reputation: 37

Showing 2 different states from the same reducer without the state rewrites itself

I'm building a large application that fetches different music audio and videos from the same reducer and I wanted to fetch the latest 5 music audios and videos from the reducer but both of them are in the same reducer, how do I get both data without them rewriting each other as I use the actions?

Upvotes: 0

Views: 41

Answers (1)

Hazemdido
Hazemdido

Reputation: 106

I don't get your question clearly and i think it better to post your code.

But if i got u right i think you are using the same object to store both of them. Your code should be something like this.

at reducer.js

const INITIAL_STATE = {
    musicList: [],
    videoList: []
};

export function reducerX(state = INITIAL_STATE, action) {
    switch (action.type) {
        case 'FETCHING_MUSIC_SUCCESS':
            return {
                ...state, musicList: action.payload, loading: false
            };
        case 'FETCHING_MUSIC_LOADING':
            return { ...state, loading: true };

        case 'FETCHING_MUSIC_FAILED':
            return {
                ...state,
                error: 'failed to fetch music',
                loading: false
            };

        case 'FETCHING_VIDEO_SUCCESS':
            return {
                ...state, videoList: action.payload, loading: false
            };
        case 'FETCHING_VIDEO_LOADING':
            return { ...state, loading: true };

        case 'FETCHING_VIDEO_FAILED':
            return {
                ...state,
                error: 'failed to fetch video',
                loading: false
            };
    }
}


at actionX.js

export function fetchMusic() {
    return dispatch => {
        dispatch({
            type: 'FETCHING_MUSIC_LOADING'
        });
        return API.get('/app/rest/music')
            .then(({ data: music }) =>
                dispatch({
                    type: 'FETCHING_MUSIC_SUCCESS',
                    payload: music
                })
            )
            .catch(error => dispatch({ type: 'FETCHING_MUSIC_FAILED', payload: error }));
    };
}

export function fetchVideo() {
    return dispatch => {
        dispatch({
            type: 'FETCHING_VIDEO_LOADING'
        });
        return API.get('/app/rest/video')
            .then(({ data: video }) =>
                dispatch({
                    type: 'FETCHING_VIDEO_SUCCESS',
                    payload: video
                })
            )
            .catch(error => dispatch({ type: 'FETCHING_VIDEO_FAILED', payload: error }));
    };
}

Upvotes: 1

Related Questions