首页 > 解决方案 > How to re-fetch data in react-apollo with value from the another input component?

问题描述

I have next issue with react-apollo: there are two components and both are located in totally different places:

<Query
  query={OFFERS_QUERY}
  variables={{ page: 1, keyword: 'SomeDefaultKeyword' }}
>
        {({ error, data, loading, fetchMore, client }) => {

          if (error) {
            return <div>Something went wrong. {error.message}</div>;
          }

          if (loading) {
            return <Loader />;
          }

          const { search: { metadata, offers }} = data;

          return (
            <InfiniteScroll
              hasMore={metadata.hits > 0}
              loader={<Loader />}
              loadMore={pageNumber => {
                fetchMore({
                  updateQuery: (prev, { fetchMoreResult } )=> {
                    if (!prev.fetchMoreResult) return prev;

                    return {
                      search: {
                        __typename: prev.search.__typename,
                        criteria: fetchMoreResult.search.criteria,
                        metadata: prev.search.metadata,
                        offers: [
                          ...prev.search.offers,
                          ...fetchMoreResult.search.offers,
                        ],
                      },
                    };
                  },
                  variables: {
                    keyword: ?,
                    page: ?,
                  },
                });
              }}
              useWindow={true}
            >
              <List>
                {offers.map( offer  => (
                  <ListItem key={offer.id}>
                    <OfferCard description={offer.name} />
                  </ListItem>
                ))}
              </List>
            </InfiniteScroll>
          );
        }}
</OffersQuery>

Questions:

  1. How can I make next request in the <OfferList /> using fetchMore with new keyword provided by user in the <Search />?
  2. How would you suggest to reset page number when user typed new keyword (needs to be 1 in that case)?
  3. User see offers list and spinner when scrolling down, but when user click I need spinner without products to be shown. Do you have any ideas?

I was thinking if there is some mechanism that allows me to save value from input to the apollo store and can force update in <Query />. In that case it solves the problem, but I didn't get how I can do that correct. I was trying to call client.writeQuery, client.watchQuery, client.writeData as input onChage callback, but looks like it doesn't execute force <Query /> re-render. If you have experience to work with such case would be nice if you can share some ideas to me.

标签: reactjsreact-apolloapollo-clientgraphql-js

解决方案


推荐阅读