Blog>
Snippets

Initializing Redux Store for Tracking User Progress

Showcase the creation of a Redux store with initial state representing a user's progress in various courses within an e-learning platform.
import { createStore } from 'redux';

// Define the initial state of the user's progress
const initialState = {
    coursesInProgress: {},
    coursesCompleted: {}
};

// Define the reducer to handle actions
const progressReducer = (state = initialState, action) => {
    switch (action.type) {
        case 'START_COURSE':
            return {
                ...state,
                coursesInProgress: {
                    ...state.coursesInProgress,
                    [action.courseId]: { completed: false, progress: 0 }
                }
            };
        case 'UPDATE_PROGRESS':
            return {
                ...state,
                coursesInProgress: {
                    ...state.coursesInProgress,
                    [action.courseId]: { ...state.coursesInProgress[action.courseId], progress: action.progress }
                }
            };
        case 'COMPLETE_COURSE':
            const { [action.courseId]: completedCourse, ...remainingCourses } = state.coursesInProgress;
            return {
                ...state,
                coursesInProgress: remainingCourses,
                coursesCompleted: {
                    ...state.coursesCompleted,
                    [action.courseId]: { completed: true, progress: 100 }
                }
            };
        default:
            return state;
    }
};

// Create the store with the reducer
const store = createStore(progressReducer);

export default store;
This code initializes a Redux store with an initial state representing the progress of a user in various courses. It includes actions to start a course, update progress, and mark a course as completed.