Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

99
Vistas
Having issues reupdating the UI when submitting form that calls an endpoint in React

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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()
  }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda