jeninja
jeninja

Reputation: 848

React Redux not updating state

I am using the React Hooks implementation of React-Redux. Below is the flow of my code. For some reason any values that I pass in my dispatch(fuction(value)) is not detected in my reducer. I can't figure it out.

src/components/categories/selectCategory.tsx

    import React from 'react';
    import {useDispatch} from 'react-redux';
    import {setCategory} from '../../store/actions';

    const selectCategory = (name: string) => {
        dispatch(setCategory(name)); // ex: name = 'algebra'
    };

store/actions/index.ts

export const setCategory = (name) => ({
    type: 'SET_CATEGORY',
    name: name
});

store/reducers/index.ts

import {combineReducers} from 'redux';
import category from './category';

const app = combineReducers({
    category
});

export default app;

store/reducers/category.ts

const initialState = {
    name: 'calculus'
};

const category = (state = initialState, action) => {
    switch (action.type) {
        case 'SET_CATEGORY':
            return {name: state.name}; // outputs 'calculus'
        default:
            return state;
    }
};

export default category;

I'm sure there is some small detail I am missing.

Upvotes: 0

Views: 254

Answers (1)

jeninja
jeninja

Reputation: 848

My issue was fixed by returning the action.name property instead of state.name.

store/reducers/category.ts

const initialState = {
    name: 'calculus'
};

const category = (state = initialState, action) => {
    switch (action.type) {
        case 'SET_CATEGORY':
            return {name: action.name};
        default:
            return state;
    }
};

export default category;

Upvotes: 2

Related Questions