I'm working through a React tutorial and can't get past this error:
I have this ArticlePage which gets articleInfo
from state and then sends it as a parameter to UpvotesSection.js
:
const ArticlePage = ({ match }) => {
const name = match.params.name;
const article = articleContent.find(m => m.name === name);
const [articleInfo, setArticleInfo] = useState({ upvotes: 0, comments: [] });
useEffect(() => {
const fetchData = async () => {
const result = await fetch(`/api/articles/${name}`);
const body = await result.json();
setArticleInfo(body);
};
fetchData();
}, [name]);
if (!article) return <NotFoundPage />;
const otherArticles = articleContent.filter(m => m.name !== name);
return (
<>
<h1>{article.title}</h1>
<UpvotesSection articleName={name} upvotes={articleInfo.upvotes} setArticleInfo={setArticleInfo} />
{article.content.map((text, key) => (
<p key={key}>{text}</p>
))}
<CommentsList comments={articleInfo.comments} />
<ArticlesList articles={otherArticles} />
</>
)
}
In UpvotesSection.js
, I simply display it:
import React from 'react';
const UpvotesSection = (articleName, upvotes, setArticleInfo) => {
const upvoteArticle = async () => {
const result = await fetch(`/api/articles/${articleName}/update`, {
method: 'post'
});
const body = result.json;
setArticleInfo(body);
}
return (
<div className="upvotes-section">
<button onClick={() => upvoteArticle()}>Add Upvote</button>
<p>This article has been upvoted {upvotes} times.</p>
</div>
);
};
export default UpvotesSection;
The error is this:
Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.
in p (at UpvotesSection.js:16)
in div (at UpvotesSection.js:14)
in UpvotesSection (at ArticlePage.js:31)
in ArticlePage (created by Context.Consumer)
in Route (at App.js:27)
in Switch (at App.js:23)
in div (at App.js:22)
in div (at App.js:20)
in Router (created by BrowserRouter)
in BrowserRouter (at App.js:18)
in App (at src/index.js:9)
in StrictMode (at src/index.js:8)
If I don't display upvotes in UpvotesSection.js
, then I don't get the error, but upvotes is an integer, not a JavaScript Object.
What could be causing this problem?