Home > OS >  Having issues reupdating the UI when submitting form that calls an endpoint in React
Having issues reupdating the UI when submitting form that calls an endpoint in React

Time:10-18

I'm fetching a median prime number from an Express server function. Then, I want to update the number to check for its median value on the frontend.

However, when I try to fetch the endpoint & update UI in the handleSubmit function & update the state with this.setState({ medianPrimeNumber: this.fetchMedianPrimeNumber(parseInt(this.state.formValue)) }) , I get the following error describe:

Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

It seems that this.state.medianPrimeNumber returns a Promise when I submitted the form. I am not sure how to fix this:

import { React, Component } from 'react';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      medianPrimeNumber: null,
      formValue: ''
    };

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

  handleChange(e) {
    this.setState({ formValue: e.target.value })
  }

  handleSubmit(e) {
    this.setState({ medianPrimeNumber: this.fetchMedianPrimeNumber(parseInt(this.state.formValue)) })
    e.preventDefault()
  }

  componentDidMount() {
    this.fetchMedianPrimeNumber(17)
      .then(res => this.setState({ medianPrimeNumber: res.server
        }))
      .catch(err => console.log(err))
  }
    
  fetchMedianPrimeNumber = async (numberToCheck) => {
    const response = await fetch(`/median-prime-number/${numberToCheck}`)
    const body = await response.json()

    if (response.status !== 200) {
      throw Error(body.message) 
    }

    return body;
  };
  
  render() {
    return (
      <div className="App">
        <h1>Median Number Playground</h1>
        { this.state.formValue }
        <p className="App-intro">{ this.state.medianPrimeNumber}</p>
        <form onSubmit={this.handleSubmit}>
          <label>
            Enter number:
            <input type="text" value={this.state.formValue} onChange={this.handleChange} />
          </label>
      </form>
      </div>
    );
  }
}

export default App

formValue's state updates properly

CodePudding user response:

You are correct,this.fetchMedianPrimeNumber(parseInt(this.state.formValue)) }) does return a promise.

You want the value thats coming back as a result of that promise. In otherwords, you want to await the value since its an async function. i.e:

  async handleSubmit(e) {
    const res = await this.fetchMedianPrimeNumber(parseInt(this.state.formValue))
    this.setState({ medianPrimeNumber: res })
    e.preventDefault()
  }
  • Related