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
CodePudding user response:
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.