I'm trying out React hooks, and I'm very confused about what I'm seeing. I'm getting a JS object as a payload from my endpoint, and this will display and render fine if I pass the raw result:
...
import React, { useEffect, useState } from 'react'
const Status = () => {
const [data, setData] = useState({})
useEffect(() => {
console.log('fetching status')
const start = new Date()
getStatus()
.then(result => {
console.log(`status fetched in ${(new Date() - start)}`)
for (const key of Object.keys(result)) {
if (!data[key]) {
data[key] = {}
}
data[key]['status'] = result[key]
}
console.log(data);
setData(result)
})
.catch(err => console.error(err))
}, [])
return (
<div>
{ console.log('rendering')}
<h1>Status</h1>
<span>{JSON.stringify(data)}</span>
</div>
)
}
export default Status
... and I get two "rendering" logs as expected.
But when I change it to actually use the processed data instead:
...
import React, { useEffect, useState } from 'react'
const Status = () => {
const [data, setData] = useState({})
useEffect(() => {
console.log('fetching status')
const start = new Date()
getStatus()
.then(result => {
console.log(`status fetched in ${(new Date() - start)}`)
for (const key of Object.keys(result)) {
if (!data[key]) {
data[key] = {}
}
data[key]['status'] = result[key]
}
console.log(data);
setData(data) // <--- here
})
.catch(err => console.error(err))
}, [])
return (
<div>
{ console.log('rendering')}
<h1>Status</h1>
<span>{JSON.stringify(data)}</span>
</div>
)
}
export default Status
I don't get that second render, and the information isn't rendered on the page. Data is there as I verified in the console.log statement.