Reputation: 1351
I'm new to React and Redux so this could be the complete wrong way to go about things, but I'm trying to get the updated state within an onSubmit
method.
This is a simple flashcard app and what I want to happen is to get a sentence from the user (userInput
) and compare it against the correct sentence (generated
). I'm able to get a list of correct and incorrect words based on their submission (done with the compareInput()
action) which I can see in the Redux state, but this isn't updated until after method completely runs, so the way I currently have it set up, the initial length of the vectors correct
and wrong
are 0.
How can I get the updated state within the method? Or is there a better way to do this? I can do it in componentDidUpdate
, but since the state is updating with each change in the form, I thought it would be unnecessary overhead calculate the correct percentage (pctCorrect
) each update.
Thanks a ton!
Input.js
:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import {
compareInput, generateSentence, trackProgress
} from '../../actions/learn';
export class Input extends Component {
state = {
userInput: '',
progress: { submissions: 0, pctCorrect: 1 },
}
onSubmit = e => {
e.preventDefault();
const { sentence } = this.props.sentence;
const { userInput } = this.state;
this.props.compareInput({
'generated': sentence,
'user_input': userInput,
});
this.props.generateSentence();
this.setState({ userInput: '' })
this.props.trackProgress({
progress: {
submissions: this.props.progress.submissions + 1,
pctCorrect: this.props.correct.length / (
this.props.correct.length + this.props.wrong.length
)
},
})
render() { };
const mapStateToProps = state => ({
sentence: state.learnReducer.sentence,
progress: state.learnReducer.progress,
correct: state.learnReducer.correct,
wrong: state.learnReducer.wrong,
})
export default connect(mapStateToProps, {
compareInput, generateSentence, trackProgress
})(Input);
Upvotes: 0
Views: 95
Reputation: 67459
React components can't access newer values from props until they re-render. Doesn't matter whether it's a class or function component, or if the component is dispatching a Redux action or a callback from a parent. React hasn't yet been able to re-render by the time the next line runs, and props
will still be pointing to the existing props anyway.
If you absolutely need to access the latest values from the Redux store immediately after dispatching an action, move the logic into a thunk so that you have access to getState
:
// An example of checking state after a dispatch
function checkStateAfterDispatch() {
return (dispatch, getState) => {
const firstState = getState();
dispatch({type : "FIRST_ACTION"});
const secondState = getState();
if(secondState.someField != firstState.someField) {
dispatch({type : "SECOND_ACTION"});
}
}
}
Upvotes: 1