texas697
texas697

Reputation: 6387

How to setup redux saga

I am trying to setup redux-saga but I am not sure if that is causing the problem.

Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.

It is a common error but I cannot figure this out. I have used examples from redux and redux-saga to setup code.

class Login extends Component {
  static propTypes = {
    isAuthenticated: PropTypes.bool,
    loginRequest: PropTypes.func
  }

  _onSubmit = () => {
    const {userName, password} = this.state

    const credentials = { userName, password }
    this.props.loginRequest(credentials)
  }
}

const mapStateToProps = state => ({
  isAuthenticating: state.login.isAuthenticating
})

const mapDispatchToProps = dispatch => bindActionCreators({
  loginRequest
}, dispatch)

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Login)

./action

export const loginRequest = credentials => {
  return dispatch => {
    dispatch({
      type: types.LOGIN_REQUEST,
      credentials
    })
  }
}

./store

export const history = createHistory()
const sagaMiddleware = createSagaMiddleware()

const initialState = {}
const enhancers = []
const middleware = [
  sagaMiddleware,
  routerMiddleware(history)
]

const composedEnhancers = compose(
  applyMiddleware(...middleware),
  ...enhancers
)

const store = createStore(
  rootReducer,
  initialState,
  composedEnhancers
)

sagaMiddleware.run(loginSaga)

export default store

./saga

    function postLogin (credentials) {
  credentials.grant_type = 'password'
  const payload = {
    method: 'post',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    data: encoder(credentials),
    url: `${config.IDENTITY_URL}/Token`
  }

  return axios(payload)
}

function * loginRequest (action) {
  try {
    const data = yield call(postLogin, action.credentials)
    yield put({ type: types.LOGIN_SUCCESS, data })
  } catch (err) {
    yield put({ type: types.LOGIN_FAILURE, err })
  }
}

function * loginSaga () {
  yield takeLatest('LOGIN_REQUEST', loginRequest)
}

export default loginSaga

Upvotes: 0

Views: 498

Answers (1)

madox2
madox2

Reputation: 51841

The problem is exactly described in error message, your actions have to be plain objects. That means your action creators have to return plain objects, e.g.:

export const loginRequest = credentials => {
  return {
    type: types.LOGIN_REQUEST,
    credentials
  }
}

Upvotes: 1

Related Questions