I had a question, and a problem when rendering Json data with react js. I Couldn't get react to map out the data. Here is my code:
My Json:
res.json({
list: [{id: 1, name: 'Caleb'}, {id: 2, name: 'Isaiah'}]
})
My React Code:
import { useState, useEffect } from 'react'
function App() {
const [data, setData] = useState({})
useEffect(() => {
fetch("/home")
.then(res => res.json())
.then(data => setData(data))
}, [])
return (
<div>
{data.list.map(function(d, idx){
return (<li key={idx}>{d.name}</li>)
})}
</div>
);
}
export default App;
Its giving me this error, that it cant render it properly.
The simplest way to achieve your goal is to use conditional rendering (&&), you can put the JSON data in a variable, but it's not necessary. Another improvement is to use the object id as the key and not the index.
Here's an example of how to improve your code:
import { useState, useEffect } from 'react';
function App() {
const [data, setData] = useState({});
useEffect(() => {
fetch("/home")
.then(res => res.json())
.then(data => setData(data))
}, [])
return (
<div>
{data.list && (
data.list.map(function (d) {
return <li key={d.id}>{d.name}</li>;
})
)
</div>
);
}
export default App;
I fixed it by first putting the Json data into a variable, then made sure that the variable wasn't undefined, then rendered it! Like this:
import { useState, useEffect } from 'react'
function App() {
const [data, setData] = useState({})
useEffect(() => {
fetch("/home")
.then(res => res.json())
.then(data => setData(data))
}, [])
const new_data = data.list;
const renderAuth = () => {
if (new_data !== undefined) {
return (
<div>
{new_data.map(function(d, idx){
return (<li key={idx}>{d.name}</li>)
})}
</div>
);
} else {
console.log("sorry had problems")
}
}
return (
<div>
{renderAuth()}
</div>
);
}
export default App;
Then it worked like a charm! No problems at all.