Search code examples
javascriptreactjsreduxreducers

return (dispatch) do nothing


i have a component which run this

 import { handleAddQuestion } from '../actions/questions';

 handleAddQuestion(optionOneText, optionTwoText, author)

in actions/questions i have

import { _saveQuestion } from '../utils/_DATA';
export function handleAddQuestion (optionOneText, optionTwoText, authedUser) {
  console.log("before")
  return (dispatch) => {
    console.log("after")
    _saveQuestion({optionOneText, optionTwoText, author: authedUser}).then((question) => {
      let qid = question.id
      dispatch(saveUserQuestion(authedUser, qid))
      dispatch(addQuestion(question))
    })
  }

}

i get before in console but not after no action is triggered, nothing happens at all no matter what i change ,, it's like i cannot do this return (dispatch) !! i tried the same thing in another place which worked perfectlly, logged the data and triggered the actions ! what is wrong here !!!!!!!

more info _DATA_.js

export function _saveQuestion (question) {
  return new Promise((res, rej) => {
    const authedUser = question.author;
    const formattedQuestion = formatQuestion(question);

    setTimeout(() => {
      questions = {
        ...questions,
        [formattedQuestion.id]: formattedQuestion
      }
      
      users = {
        ...users,
        [authedUser]: {
          ...users[authedUser],
          questions: users[authedUser].questions.concat([formattedQuestion.id])
        }
      }

      res(formattedQuestion)
    }, 1000)
  })
}

reducers/questions.js

export function questions(state = {}, action) {
    switch (action.type) {
      case ADD_QUESTION:
        const { question } = action;
        return {
            ...state,
            [question.id]: question,
        };
    ///

any help ?


Solution

  • You are returning what is called a thunk here - and thunks only get executed when actually being dispatched. Compare that with how it is called in the other places.

    So correct would be calling

     dispatch(handleAddQuestion(optionOneText, optionTwoText, author))