Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
94 views
in Technique[技术] by (71.8m points)

javascript - Apollo state management inside a component

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As mentioned in the comments, you're getting the error because some hook is being rendered conditionally.

You can't call hooks inside loops, conditions, or nested functions, you need to call them at the top level of your component. This allows React to correctly preserve the state of hooks by ensuring hooks are called in the same order each time a component renders.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...