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

604 views Asked by At

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

2

There are 2 answers

3
Giorgio Bozio On BEST ANSWER

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)
0
Joe On

the issue really was from where to dispatch the action changing the url. The answer came from Giorgio Bozio's answer and then:

  1. https://github.com/redux-saga/redux-saga/issues/79#issuecomment-215665308 - being the three ways to change the url.

  2. specifically, I used import { push } from 'react-router-redux'

  3. but I had an issue with how to configure the middleware and this link solved it for me: https://github.com/reactjs/react-router-redux/issues/366#issuecomment-212044390