0

I have the following actions code:

let nextTodoId = 0

export const addTodo = text => ({
  type: 'ADD_TODO',
  id: nextTodoId++,
  text
})
 
export const setVisibilityFilter = filter => ({
  type: 'SET_VISIBILITY_FILTER',
  filter
})
 
export const toggleTodo = id => ({
  type: 'TOGGLE_TODO',
  id
})

export const getResult = () => { type: 'GET_RESULT' }
 
export const VisibilityFilters = {
  SHOW_ALL: 'SHOW_ALL',
  SHOW_COMPLETED: 'SHOW_COMPLETED',
  SHOW_ACTIVE: 'SHOW_ACTIVE'
}

when "getResult" gets dispatched I get this error: "actions must be plain objects".

Am I not returning an object like this?

export const getResult = () => { type: 'GET_RESULT' }

If I change the above to:

export const getResult = { type: 'GET_RESULT' }

then it's all good

enter image description here

even after modifying the code with the possible solutions, I am still getting the error

Aessandro
  • 5,517
  • 21
  • 66
  • 139

3 Answers3

3

Wrap your object in braces otherwise the function will return undefined.

export const getResult = () => ({ type: 'GET_RESULT' });

You also need to call your getResult function inside the dispatch.

getResult: () => dispatch(getResult())
Andy
  • 61,948
  • 13
  • 68
  • 95
2

Your code

export const getResult = () => { type: 'GET_RESULT' }

transpiles into

var getResult = function() { 
    { type: 'GET_RESULT' }
};

which returns undefined, hence the error. If you change it into expression it will work:

export const getResult = () => ({ type: 'GET_RESULT' })

That's because it transpiles into:

var getResult = function() { 
    return { type: 'GET_RESULT' };
};
Vilius Paulauskas
  • 3,121
  • 3
  • 24
  • 24
0

No you're not without parens you are creating an arrow function body, just use the syntax you've used above:

export const getResult = () => ({ type: 'GET_RESULT' });
t3__rry
  • 2,817
  • 2
  • 23
  • 38