Josh L
Josh L

Reputation: 1492

Fetching single item vs fetching multiple items with Redux

I'm currently working on application that has the following:

My coursesAction file has an action function for fetching a single course from the server and another action function for fetching all courses from the server. Should I use a seperate reducer for handling a list of courses vs a single course since my initialState is an empty array (meant for a list of course objects)? rather than an empty object(meant for a course object)?:

let initialState =  [];

export default function courseReducer(state = initialState, action){
    switch(action.type){
        case types.LOAD_COURSES_SUCCESS:
            return  action.courses;    
        default:
            return state;
    }
}

Or should I instead retrieve all courses from the server and then when navigating to my 'course' page query the course I'm looking for from the store??

Upvotes: 1

Views: 2123

Answers (1)

Parag Soni
Parag Soni

Reputation: 713

Well create two reducers for two different actions is not a bad idea but if you just want to separate it due to initial state datatype problem then you do not need to make it separate. Both can be handled in a single way. Use immutable, which is also a good practice if you are using react + rediux

Import immutable

import {Record} from 'immutable'

Make initial state object as follow

const Initialstate = new Record({
    course: {},
    courses: []
})

Your reducer be like

export default function courseReducer(state = new Initialstate(), action = {}){
    switch(action.type){
        case types.LOAD_COURSES_SUCCESS:
            return  action.courses;
        case types.LOAD_COURSE_SUCCESS:
            return  action.course;    
        default:
            return state;
    }
}

Also, you can change state in reducer like below, if require in future.

case types.LOAD_CUSTOM:
            return state.set("customPhase", "success")

Upvotes: 4

Related Questions