Reputation: 1551
I'm trying to do a simple task. Rendering contents of an array:
const [comments, setComments] = useState([]); // an array to begin with
handleFetch = () => {
...
...
const obj = resp.data.comments;
const new_array = new Array();
new_array.push(obj);
setComments(new_array);
...
}
return (
{comments.forEach(comm => <p>{comm.post}</p>)}
);
comments (resp.data.comments
) come in as an array of objects:
comments = [{'post': 'something', 'timestamp': 'some time'}]
Error output I'm getting:
Error: Objects are not valid as a React child (found: object with keys {post, timestamp}). If you meant to render a collection of children, use an array instead.
(But I'm using an array. An array of objects)
Upvotes: 1
Views: 60
Reputation: 2121
Since resp.data.comments
is an array, you can directly set to it to state comments using setComments(resp.data.comments)
and use Array.prototype.map
function in jsx to render.
const [comments, setComments] = useState([]); // an array to begin with
handleFetch = () => {
...
...
setComments(resp.data.comments);
...
}
return (
<>
{comments.map(comm => <p>{comm.post}</p>)}
</>
);
Upvotes: 3
Reputation: 12787
You need to use .map()
to return the value. So you can fix like this:
return (
<>
{comments.map((comm, index) => <p key={index}>{comm.post}</p>)}
</>
);
Upvotes: 1