'Too many re-renders. React limits the number of renders
Im trying to save my articles object from my graphql server to the state, but its giving me this error "too many re-renders" when I try to save them to the state
I checked with a console.log on the client and the method getNews() is giving me the correct output object with my x50 article object, but when I try to save it to the state, it crashes
import React from "react";
import Layout from "../components/Layout";
import Article from "../components/Article";
import { useState, useEffect } from "react";
import { gql, useQuery } from "@apollo/client";
const News = () => {
const [articles, setArticles] = useState([]);
const getNews = () => {
const LATEST_NEWS = gql`
query {
getNews {
title
}
}
`;
const { data } = useQuery(LATEST_NEWS);
const myArticles = data.getNews;
return myArticles;
};
useEffect( () => {
setArticles(getNews())
},[])
console.log(articles)
return (
<>
<Layout page="News" />
<h1 className="text-xl text-center text-gray-800 font-bold m-8">
The latest news about crypto!
</h1>
{/* <div className="grid grid-cols-1 gap-3 text-center m-8 md:grid-cols-3">
{articles.map((article) => (
<Article key={article.id} article={article} />
))}
</div> */}
</>
);
};
export default News;
Solution 1:[1]
I am not entirely familiar with @apollo/client, but useQuery like all hooks, should be in the root of your component.
You could probably do without the state and effect, something like this:
import React from "react";
import { gql, useQuery } from "@apollo/client";
import Layout from "../components/Layout";
import Article from "../components/Article";
const LATEST_NEWS = gql`
query {
getNews {
id
title
}
}
`;
const News = () => {
const { data } = useQuery(LATEST_NEWS);
const articles = data.getNews;
if (!articles) {
return null; // Or loading, or something else
}
return (
<>
<Layout page="News" />
<h1 className="text-xl text-center text-gray-800 font-bold m-8">
The latest news about crypto!
</h1>
<div className="grid grid-cols-1 gap-3 text-center m-8 md:grid-cols-3">
{articles.map((article) => (
<Article key={article.id} article={article} />
))}
</div>
</>
);
};
export default News;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
