0

I'm unable to update the state using the axios response in a class component. It works just fine with function based components. Could somebody please point out what is causing this issue. I'm new to react and tried most of the possible answers out there.

code :

import React, { Component } from "react";
import "./Table.css";
import { Button } from "./Button";
import { Table } from "react-bootstrap";
import axios from "axios";
import Example from "./Progress";

class Tables extends Component {
  constructor(props) {
    super(props);
    this.state = {
      submitted: false,
      task_id: "",
    };
    this.handlesubmit = this.handlesubmit.bind(this);
  }

  handlesubmit(event) {
    var self = this;
    event.preventDefault();
    axios({
      method: "post",
      url: "http://127.0.0.1:8000/api/test/",
      data: {
        project_name: "test",
      },
    }).then(function (response) {
      console.log(response.data.task_id); //prints taskid (12345678)
      self.setState({
        task_id: response.data.task_id,
      });
      console.log(self.task_id); //prints undefined
    });
    this.setState({ submitted: true }); //works fine, state is set to true
    console.log(this.task_id); //prints undefined
  }

  render() {
    let modal;
    let task_id = this.state.task_id;
    let submitted = this.state.submitted;
     if (submitted === true) {
     modal = <Example pro="test" task={task_id} />;
      }

    return (
      <div className="table-div">
        <Button
          buttonStyle="btn--secondary"
          buttonSize="btn--small--opt"
          onClick={this.handlesubmit}
        >
          test
        </Button>
        {modal}
      </div>
    );
  }
}

export default Tables;
LiquidDeath
  • 1,768
  • 1
  • 7
  • 18
  • Does this answer your question? [React setState not Updating Immediately](https://stackoverflow.com/questions/38558200/react-setstate-not-updating-immediately) – goto Apr 11 '21 at 13:40
  • `setState` is asynchronous and it will update `task_id` on the next render. Also, `setState` takes a callback - `this.setState({}, () => { console.log(this.task_id) })` that you can use if you need access the updated state after you call `setState`. – goto Apr 11 '21 at 13:40
  • @goto1, actually after the response is received, i need to send it to another component. since it is showing undefined it throws an error. tbh, this is my first time with react and i'm not understanding most of the parts. If you could show where to add this callback, it would be a great help – LiquidDeath Apr 11 '21 at 13:47
  • How are you "sending it to another component?" – goto Apr 11 '21 at 13:49
  • that part i hadn't added to the code here. now updated, please check – LiquidDeath Apr 11 '21 at 13:53

1 Answers1

1

You should update your state inside then when the axios call succeeds:

handleSubmit(event) {
  event.preventDefault();
  axios({...})
    .then((response) => { 
      this.setState({
        task_id: response.data.task_id,
        submitted: true
      })
    })
    .catch((error) => { /* handle errors appropriately */ })
}

Then, inside your render method, make sure that both task_id and submitted have appropriate values before rendering the modal:

render() {
  const { task_id, submitted } = this.state
  const modal = submitted && task_id !== ""
    ? <Example pro="test" task={task_id} />
    : null // don't render anything

  return (
    <div className="table-id">
      <Button ...>test</Button>
      {modal}
    </div>
  )
}
goto
  • 4,336
  • 15
  • 20