much thanks for being out here. I am new to Apollo and React and I must be not understanding the logic over here, so please bear with me
On my main page index.js, I am initializing Apollo like this:
export const getStaticProps = async () => {
const apolloClient = initializeApollo();
await apolloClient.query({
query: GET_ALL_COUNTRIES_MAIN,
variables: {
offset: 0,
limit: 30,
},
});
return {
props: { initialApolloState: apolloClient.cache.extract() },
revalidate: 1,
};
};
and calling a component <TotalCountriesMain />
which then renders all my cards. This works perfectly.
Yet inside of this component, I would like to fetchMore
so that my other result appends to the old state. So I first tried it inside "index.js" to make sure that it works, which it did. But whenever I call the fetchMore method inside it gives me this error:
Rendered fewer hooks than expected. This may be caused by an accidental early return statement.
How to prevent this from happening?
I will show you what I am doing inside my component TotalCountriesMain
below:
const [limit, setLimit] = useState(30);
const { data, error, loading, fetchMore, networkStatus } = useQuery(
GET_ALL_COUNTRIES_MAIN_NEW,
{
notifyOnNetworkStatusChange: true,
variables: {
offset: 0,
limit,
},
}
);
if (!data || !data.globaldatasortednew) return <CircularProgress />;
{data.globaldatasortednew
? data.globaldatasortednew.map((country, index) => {
return (
... // mapping over the cards
)
<Button
onClick={() => {
const currentLength = data.globaldatasortednew.length;
fetchMore({
variables: {
offset: currentLength,
limit: 50,
},
}).then((fetchMoreResult) => {
setLimit(
currentLength + fetchMoreResult.data.globaldatasortednew.length
);
});
}}
>
Show more countries
</Button>
I skipped some parts of the code that I think were irrelevant. The situation is like this:
Whenever I click the button, the error message appears. Should I somehow listen to the changes of my data? Should I create a new state such as const [allCountries, setAllCountries] = useState(initialData);
and then create some function to set all countries? Is there something I should tell the Apollo cache when doing this?
What is the best approach in this situation?
Thank you for your advice!
question from:
https://stackoverflow.com/questions/66065428/apollo-state-management-inside-a-component