Get figure from function and set it as state once user types in input

Viewed 32

I have a component that I want to use to update a 'balance' in a database.

To do this, I am pulling the figure in my componentDidMount using axios.get:

componentDidMount() {
  axios.get("/api/fetch/fetchEditDebt", {
      params: {
        id: this.props.match.params.id
      }
    })
    .then((response) => {
      this.setState({
        balance: response.data.balance,
      })
    })
}

I then have an input which takes the amount the user wants to add to the balance:

<form method="POST" onSubmit={this.onSubmit}>
  <input className="edit-balance-input" type="number" name="add" value={this.state.add} onChange={this.onChange} step="1" />
  <button className="edit-balance-button" type="submit">Save</button>
</form>

I then use a function to take the original balance from state, and the 'add' figure from the input state, and add them together:

const calculateUpdatedBalance = () => {
  return parseInt(this.state.balance) + parseInt(this.state.add)
}

And this updated figure is then rendered inside of a span so the user can see the new balance:

<div className="edit-balance-balance-container">
  <p className="edit-balance-balance-paragraph">Updated balance: </p>
  <span className="edit-balance-updated">-£{calculateUpdatedBalance()}</span>
</div>

This all works great, and as expected - the difficulty comes in when I then want to post the updated balance to my database. I tried to post the add state, but unsurprisingly that just updates the balance to the amount the user put into the input.

So how do I access the figure generated by my calculateUpdatedBalance() function? I thought about trying to setState() in the function, but that produces a "too many state updates" error.

Does anyone have any suggestions for how I can get that updated figure, and post that to my database?

Here's my full component for reference:

class Add extends Component {
  constructor(props) {
    super(props)

    this.state = {
      balance: '',
      add: 0,
      updatedBalance: '',
      fetchInProgress: false
    }

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

  componentDidMount() {
    this.setState({
      fetchInProgress: true
    })

    axios.get("/api/fetch/fetchEditDebt", {
        params: {
          id: this.props.match.params.id
        }
      })
      .then((response) => {
        this.setState({
          balance: response.data.balance,
          fetchInProgress: false
        })
      })
      .catch((error) => {
        this.setState({
          fetchInProgress: false
        })
        if (error.response) {
          console.log(error.response.data);
          console.log(error.response.status);
          console.log(error.response.headers);
        } else if (error.request) {
          console.log(error.request);
        } else {
          console.log('Error', error.message);
        }
        console.log(error.config);
      })
  }

  onChange = (e) => {
    this.setState({
      [e.target.name]: e.target.value
    })
    console.log(this.state.add)
  }

  onSubmit = async(e) => {
    e.preventDefault();

    console.log(this.props.match.params.id)

    await axios.post("/api/edit/editDebtBalance", {
      balance: this.state.add,
    }, {
      params: {
        id: this.props.match.params.id
      }
    })

    this.props.history.push('/dashboard');
  }

  render() {
    const calculateUpdatedBalance = () => {
      return parseInt(this.state.balance) + parseInt(this.state.add)
    }

    return (
      <section className="edit-balance-section">
        <div className="edit-balance-container">
          <DashboardReturn />
          <div className="edit-balance-content">
            <p className="edit-balance-paragraph">How much would you like to add to your balance?</p>
            <div className="edit-balance-balance-container">
              <p className="edit-balance-balance-paragraph">Current Balance: </p>
              <span className="edit-balance-original">-£{this.state.balance}</span>
            </div>
            <div className="edit-balance-balance-container">
              <p className="edit-balance-balance-paragraph">Updated balance: </p>
              <span className="edit-balance-updated">-£{calculateUpdatedBalance()}</span>
            </div>
            <form method="POST" onSubmit={this.onSubmit}>
              <input className="edit-balance-input" type="number" name="add" value={this.state.add} onChange={this.onChange} step="1" />
              <button className="edit-balance-button" type="submit">Save</button>
            </form>
          </div>
        </div>
      </section>
    )
  }
}
1 Answers

If you make calculateUpdatedBalance() a member method of the Add component, then you can call it from both render() and onSubmit():

  calculateUpdatedBalance() {
    return parseInt(this.state.balance) + parseInt(this.state.add)
  }

  onSubmit = async (e) => {
    ...
    await axios.post("/api/edit/editDebtBalance", {
      balance: this.calculateUpdatedBalance(),
    ...
  };

  render() {
    return (
    ...
      <span className="edit-balance-updated">-£{this.calculateUpdatedBalance()}</span>
    ...
  }
Related