• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

100
Vistas
React Axios fetch response with error Objects are not valid as a React child

Not sure why my api response is not rendering in UI. It does successfully displayed the response in console though.

Error: Objects are not valid as a React child (found: object with keys {result}). If you meant to render a collection of children, use an array instead.

import React from 'react'
import { useState, useEffect } from 'react'
import axios from 'axios'
import * as ReactBootStrap from 'react-bootstrap'

const TextGenerator = () => {
  const [usertext, setUsertext] = useState('hello')
  let [result, setResult] = useState(null)
  let [loading, setLoading] = useState(true)

  const handleSubmit = (e) => {
    e.preventDefault()
    // const text = { usertext }

    axios
      .get(`http://127.0.0.1:8000/computer programming`)
      .then((res) => {
        console.log(res)
        console.log(res.data)
        result = res.data
        setResult({ result })
        setLoading(false)
      })
      .catch((error) => console.error(`Error: ${error}`))
  }

  return (
    <div className='text-center .w-75'>
      <br />
      <form onSubmit={handleSubmit}>
        <input
          type='text'
          required
          size='80'
          placeholder='Enter text...'
          value={usertext}
          onChange={(e) => setUsertext(e.target.value)}
        />
        <button>Generate Text</button>
      </form>
      <div>
        {loading ? <ReactBootStrap.Spinner animation='grow' /> : { result }}
      </div>
    </div>
  )
}

export default TextGenerator
almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

React sees below object when it tries to render the result in state.

{
    result: {
        result: <your_data - res.data>
    }
}

Try

{loading ? <ReactBootStrap.Spinner animation='grow' /> : result}

instead of

{loading ? <ReactBootStrap.Spinner animation='grow' /> : { result }}

React cannot render object like { result }

And It will still fail since you wrap and save the result as an object.

Change

setResult({ result })

To

setResult(result)

This will still fail if res.data is not a type of string or array of JSX/string Elements.

almost 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda