Reputation: 717
I'm trying to setup a simple form using redux-form.
Right now I just have a button, that should dispatch an action. I see the SET_SUBMIT_SUCCEEDED
action so I know the form submitted successfully, and I can see the onSubmit
function I specified is being called, but it is not dispatching an action.
// root reducer
import { combineReducers } from 'redux'
import { reducer as reduxFormReducer } from 'redux-form'
import login from './login'
export default combineReducers({
login,
form: reduxFormReducer
})
// action-creator
import { createAction } from './create_action'
import { postJson } from './fetch'
import {
LOGIN_ERROR,
LOGIN_REQUEST,
LOGIN_SUCCESS
} from '../constants/constants'
const login = () => {
return function (dispatch) {
dispatch(createAction(LOGIN_REQUEST))
return postJson('/login')
.then(res => res.json())
.then(data =>
dispatch(createAction(LOGIN_SUCCESS, { data }))
)
.catch(error => dispatch(createAction(LOGIN_ERROR, { error })))
}
}
//component
import React from 'react'
import { reduxForm } from 'redux-form'
import login from '../redux/submit-handlers/login'
const Login = (props) => {
const { handleSubmit } = props
return (
<form onSubmit={handleSubmit}>
<h3>Login</h3>
<button>Login</button>
</form>
)
}
export default reduxForm({
form: 'login',
onSubmit: login
})(Login)
//create_action
export const createAction = (type, payload) => {
return {
type,
payload
}
}
I haven't had any problems dispatching actions using this approach in other components. I must just have something configured wrong with redux, but I feel like I'm doing it just as the examples described.
If I pass the login function down in props and pass it to handleSubmit
like this
<form onSubmit={handleSubmit(() => {login()})}>
The onSubmit
function is called, but it's called before SET_SUBMIT_SUCCEEDED
which makes me think that any validation I add wouldn't work, and it would submit anyway.
Upvotes: 3
Views: 624
Reputation: 717
This worked
const login = (values, dispatch) => {
dispatch(createAction(LOGIN_REQUEST))
return postJson('/login')
.then(res => res.json())
.then(data =>
dispatch(createAction(LOGIN_SUCCESS, { data }))
)
.catch(error => dispatch(createAction(LOGIN_ERROR, { error })))
}
Upvotes: 3
Reputation: 1342
It seems that your login
function should have a different signature.
From looking at the docs http://redux-form.com/6.2.0/docs/api/ReduxForm.md/
onSubmit will be called with the following parameters:
values : Object The field values in the form of { field1: 'value1', field2: 'value2' }.
dispatch : Function The Redux dispatch function.
props : Object The props passed into your decorated component.
Try something like:
const login = ({dispatch}) => {
dispatch(createAction(LOGIN_REQUEST))
return postJson('/login')
.then(res => res.json())
.then(data =>
dispatch(createAction(LOGIN_SUCCESS, { data }))
)
.catch(error => dispatch(createAction(LOGIN_ERROR, { error })))
}
}
Upvotes: 3