Nathan Leadill
Nathan Leadill

Reputation: 114

Weird reducer redux hack

So im just using redux to dispatch an action and am still adjusting to using the hooks (ive been working for some archaic projects;

I'm calling my action like this

function generalFunction2(data) { 
        return { 
            type: constants.ACTION, data 
          } 
      }

    const generalFunction1 = (data, action) => {
        dispatch(generalFunction2(data))
    }

So then in my actual reducer file im trying to use this code

xport function generalFunction(state = initialState, data) {
    const data = action.value;
    const { type, value } = data;
    switch (action.typr) {
        case constants.ACTION:
            return {
                ...state,
                [type]: value
              };
            break;
        default:
            break;
    }
}

But i seem to be getting an undefined error on const type cannot be undefined.

Uncaught TypeError: Cannot read property 'type' of undefined

So instead im using this (what i consider a hack) anyone got any smarter/neater workarounds?

export function generalFunctionHack(state = initialState, data) {
    let type, value = "";
    if(action) {
        type = action.value.type;
        value = action.value.value;
    }
    switch (action.typr) {
        case constants.ACTION:
            return {
                ...state,
                [type]: value
              };
            break;
        default:
            break;
    }
}

Upvotes: 0

Views: 104

Answers (1)

Alex Mckay
Alex Mckay

Reputation: 3696

export function generalFunction(state = initialState, data) {
    const data = action.value; // you haven't defined action
    const { type, value } = data; // therefore data is undefined
    switch (action.typr) {}
}

Get eslint, learn how to use it well. It will eliminate errors like this.

Upvotes: 1

Related Questions