0

I'm doing a simple fetch from my backend express server.

  1. First "Submit" button click, I get "undefined".
  2. Second time "Submit" button click, I get my data as expected.

enter image description here

This would work but the user would need to click login twice (not ideal)

How can I get the results from the user's first click?

import React  from "react";
import { Button, FormGroup, FormControl, FormLabel } from "react-bootstrap";
import "./Login.css";

class Login extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
        data: []
    };

    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {

    event.preventDefault();

    fetch('/users')
      .then(response => response.json())
      .then(data => this.setState({ data }))

      console.log(this.state.data[0]);
  }

  render() {
    return (
      <div className="Login">
        <form onSubmit={this.handleSubmit}>
          <FormGroup controlId="email" bssize="large">
            <FormLabel>Email</FormLabel>
            <FormControl
              autoFocus
              type="email"
              value={this.email}
              //onChange={e => setEmail(e.target.value)}
            />
          </FormGroup>
          <FormGroup controlId="password" bssize="large">
            <FormLabel>Password</FormLabel>
            <FormControl
              value={this.password}
            // onChange={e => setPassword(e.target.value)}
              type="password"
            />
          </FormGroup>
          <Button block bssize="large" type="submit">
            Login
          </Button>
        </form>
      </div>
    );
  }
}

export default Login;

***For testing, I'm using "console.log(this.state.data[0]);"

0

1 Answer 1

1

setState doesn't reflect immediately. You might have to pass the console.log as a callback to setState

Change from

.then(data => this.setState({ data }))

to

 .then(data => this.setState({ data }, ()=>{console.log(this.state.data[0])}))

To know more about the callback and the issue.

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall

https://reactjs.org/docs/react-component.html#setstate

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

2 Comments

Even if setState was synchronous, it still wouldn't work in his question lol cos it's inside a fetch's .then, where as the console.log is outside that chain
Sorry I am not getting what you mean by setState as synchronous. setState is async and if you want to know when the update is done, you need to pass the required function as a callback. And in the answer I asked the OP to print the log inside the callback.

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.