Michael Becerra
Michael Becerra

Reputation: 411

Get id from post data react

I want to redirect to the created element right after submit. So far I have this code:

class Person extends Component {
  constructor(props) {
    super(props);
    this.state = {
      personID: 0,
      description: "",
      phone: ""
    };

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

  handleInputChange(event) {
    const target = event.target;

    const value = target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  modifyPersonID(idx) {
    this.setState({ personID: idx });
    var ruta = "/persons/" + idx + "/";
    return <Redirect to={ruta} />;
  }

  fetchData(event) {
    let idx = "";
    event.preventDefault();
    const body= {
      description: event.target.elements.descripcion.value,
      phone: event.target.elements.phone.value
    };
    fetch("http://api/", {
      method: "post",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body)
    })
      .then(function(response) {
        return response.json();
      })
      .then(function(data) {
        idx = data.id;
      });
    return idx;
  }

  handleSubmit(event) {
    let ruta = "/persons/";
    event.preventDefault();
    let id = this.fetchearData(event);
    this.setState({ personID: id });
    this.modifyID(id);
  }
}

When I'm trying to redirect to /persons/:id, the setState command for the id is executed after redirecting to /persons/:id, so it redirects to /persons/0. How can I make the set state right after the post statement returns the ID?

Upvotes: 0

Views: 2103

Answers (3)

ravibagul91
ravibagul91

Reputation: 20765

To call some function after setState you must go for a callback in setState.

Also use async/await for API call,

async handleSubmit(event) {
    let ruta = "/persons/"; //Remove this line 
    event.preventDefault();
    let id = await this.fetchearData(event);
    this.setState({ personID: id }, ()=> <Redirect to={`/person/${id}`} />); 
    this.modifyID(id); //Remove this line and modifyID function as well
  }

Upvotes: 0

Muljayan
Muljayan

Reputation: 3886

this.setState takes a callback function as it's second argument.

  modifyPersonID(idx) {
    this.setState({ personID: idx },()=>{
      var ruta = "/persons/" + idx + "/";
      return <Redirect to={ruta} />;
    });
  }

Try calling the return after the state is set as follows.

Upvotes: 1

Agustin Cornu
Agustin Cornu

Reputation: 196

Consider returning a promise instead of the id on your fetchData method. If that doesn't work for you, you can try using await

Upvotes: 1

Related Questions