Search code examples
reactjsreact-reduxreact-router-reduxredux-saga

POST request in a react/redux environment - how to get returned `_id` to redirect


The formSubmit part of my react form component is as below:

handleFormSubmission = (e) => {
  if (e) e.preventDefault()
  const { showErrors, validationErrors, ...formData } = this.state
  const { submitForm, router } = this.props
  const errors = run(formData, fieldValidations)

  let newState = update(this.state, {
    validationErrors: { $set: errors }
  })

  this.setState(newState, () => {
     if (isEmpty(this.state.validationErrors)) {
     // submitForm is an dispatches a redux action
     submitForm( formData )

     if (formData._id) {
       // the below is good on a PUT request
       router.push(`/accounts/lodgedocket/${formData._id}`)
     } else router.push(`/accounts/lodge`)
     // with the else above I have no _id to redirect to
   } else this.matterno.focus()
 })

submitForm is an dispatches a redux action, which then is then taken by redux-saga

const { payload } = yield take( constants.SUBMIT_LODGE_FORM )

The problem is that I don't know how to pick up on the new _id after the POST request has successfully completed. Should the url re-direct take place in the action file or in the component?

Maybe it is the case that I should push the url from the action, but I can't figure this out either.

I am using reactjs, redux, react-redux and react-redux-router.

thanks


Solution

  • You should add some more code. Anyway it doesn't look like really idiomatic redux.

    If you are doing Ajax calls you should have a middleware, like redux-thunk. It will dispatch an action in the Ajax callback. That action will contain the server response and be handled by a reducer. You'll get a new state with the id and thus a new component render will get it in the props.

    UPDATE:

    Since you are using redux-saga middleware, you can simply execute a call to the react-router-redux action creator in the saga Ajax callback. Doc here: https://github.com/reactjs/react-router-redux#what-if-i-want-to-issue-navigation-events-via-redux-actions

    Be sure to import browserHistory from react-router for the router middleware

    import { browserHistory } from 'react-router'
    const middleware = routerMiddleware(browserHistory)