0

I've created a class based component that renders an input field. I need the global state to update while the user types into the input. The issue is that the global state is always one step (render?) behind from what's actually in the input field. For example, when I write “winners” in the input, the state is “winner” instead. How can I fix this?

Component

class TeamCardT1 extends Component {
    constructor(props) {
        super(props);

        // local state
        this.state = {
            team_one_name: "Team One",
        };

        // bind events
        this.handleName = this.handleName.bind(this);
    };

    handleName = e => {
        this.setState({
            ...this.state,
            team_one_name: e.target.value
        });
        this.props.handleSubmit(this.state);
    };


    render() {
        const { team_one_name } = this.state;

        return (
            <>
            <div className="teamCard_container">
                <input
                type="text"
                id="team_one_name"
                name="team_one_name"
                value={team_one_name}
                onChange={this.handleName}
                maxLength="35"
                minLength="2"
                className="teamCard_teamName" />
        
                <PlayersCardT1 />
                <ScoreCard />
            </div>
        </>
        )
    };
}

index.js for the component

const mapStateToProps = ({ team_one_name }) => {
    return {
        team_one_name,
    };
};

// Dispatch 
const mapDispatchToProps = dispatch => {
    return {
        handleSubmit: (data) => { dispatch(updateTeamOneName(data)) }
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(TeamCardT1);

2 Answers 2

4

You handleSubmit with the previous state, change to the current value.

handleName = e => {
        this.setState({ team_one_name: e.target.value });
        this.props.handleSubmit(e.target.value);
    };

Notice that you already have a shallow merge with setState so you don't need to destruct this.state.

Sign up to request clarification or add additional context in comments.

Comments

0

state is one step behind because you should call the prop function as a setState callback by this way the prop function will call just after the state set.

handleName = e => { 
    this.setState({ 
        ...this.state,
        team_one_name: e.target.value
        }, () => {
        this.props.handleSubmit({value: e.target.value});
    }); 
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.