Repository navigation
feat: loads first page product gallery from Build Time (getStaticProps) + improve number of requests (+) - #2721
Conversation
…tion and search state management
|
This pull request is automatically built and testable in CodeSandbox. To see build info of the built libraries, click here or the icon next to each commit SHA. |
| const applySearchState = useApplySearchState() | ||
| useEffect(() => { | ||
| applySearchState(formatSearchState(state)) | ||
| }, []) |
There was a problem hiding this comment.
Updates the URL with the search State, which already started with fuzzy and operator from the server side. We don't need to refetch anymore (less 1 request).
There was a problem hiding this comment.
Finally!!! That's huge 🚀
| const selectedFacets = [ | ||
| ...collection?.meta.selectedFacets, | ||
| { | ||
| key: 'fuzzy', | ||
| value: serverData?.search?.metadata?.fuzzy ?? 'auto', | ||
| }, | ||
| { | ||
| key: 'operator', | ||
| value: serverData?.search?.metadata?.logicalOperator ?? 'and', | ||
| }, | ||
| ] |
There was a problem hiding this comment.
init facets also with the fuzzy and operator
| const [serverManyProductsData, serverManyProductsVariables] = | ||
| await fetchServerManyProducts({ | ||
| itemsPerPage: cmsPage?.settings?.productGallery?.itemsPerPage, | ||
| sort: cmsPage?.settings?.productGallery | ||
| ?.sortBySelection as SearchState['sort'], | ||
| term: '', | ||
| selectedFacets: data?.collection?.meta.selectedFacets, | ||
| }) |
There was a problem hiding this comment.
fetch products from SSR, also uses serverManyProductsVariables for cache mechanism.
| data: { | ||
| ...data, | ||
| ...serverManyProductsData, | ||
| }, | ||
| serverManyProductsVariables, |
There was a problem hiding this comment.
pass the fetch result to the front.
| const initialPages = params?.initialPages?.search ? [params.initialPages] : [] | ||
| const initialVariables = params?.serverManyProductsVariables | ||
| ? [getKey(params.serverManyProductsVariables)] | ||
| : [] | ||
|
|
||
| const [pages, setPages] = | ||
| useState<ClientManyProductsQueryQuery[]>(initialPages) | ||
| // We create pagesRef as a mirror of the pages state so we don't have to add pages as a dependency of the useGalleryPage hook | ||
| const pagesRef = useRef<ClientManyProductsQueryQuery[]>([]) | ||
| const pagesCache = useRef<string[]>([]) | ||
| const pagesRef = useRef<ClientManyProductsQueryQuery[]>(initialPages) | ||
| const pagesCache = useRef<string[]>(initialVariables) |
There was a problem hiding this comment.
we started the pages and the cache from PLPs with the values from server in page 0
| const hasSameVariables = deepEquals( | ||
| pagesCache.current[page], | ||
| getKey(localizedVariables) | ||
| ) |
There was a problem hiding this comment.
improves request/cache/refetch mechanism.
There was a problem hiding this comment.
question: @eduardoformiga do you have metrics for both comparison strategies that favor deepEquals here?
| const shouldFetchFirstPage = useShouldFetchFirstPage({ | ||
| page, | ||
| generatedBuildTime, | ||
| }) | ||
|
|
||
| const shouldFetch = !hasSameVariables || shouldFetchFirstPage |
There was a problem hiding this comment.
First page cache mechanism.
| // If there is no fuzzy or operator facet, we need to add them to the selectedFacets and re-fetch the query | ||
| const shouldRefetchQuery = | ||
| !queryResult.error && (!fuzzyFacetValue || !operatorFacetValue) | ||
|
|
||
| if (shouldRefetchQuery) { | ||
| if (queryResult.data) { | ||
| setState({ | ||
| ...state, | ||
| selectedFacets: [ | ||
| ...selectedFacets, | ||
| { | ||
| key: 'fuzzy', | ||
| value: queryResult.data.search.metadata?.fuzzy ?? 'auto', | ||
| }, | ||
| { | ||
| key: 'operator', | ||
| value: queryResult.data.search.metadata?.logicalOperator ?? 'and', | ||
| }, | ||
| ], | ||
| // Update the Search state (and URL) only if the values from fuzzy and operator changes | ||
| updateSearchParamsState({ | ||
| selectedFacets, | ||
| updatedFuzzyFacetValue, | ||
| updatedOperatorFacetValue, | ||
| setState, | ||
| state, | ||
| }) | ||
| } | ||
|
|
||
| // The first result is not relevant, return null data to avoid rendering the page while the query is being re-fetched | ||
| return { ...queryResult, isValidating: true, data: null } | ||
| } |
There was a problem hiding this comment.
there is no refetch to include facets values in the URL (-1 request)
| updateSearchParamsState({ | ||
| selectedFacets, | ||
| updatedFuzzyFacetValue, | ||
| updatedOperatorFacetValue, | ||
| setState, | ||
| state, |
There was a problem hiding this comment.
we just update the URL and Search State if the values from fuzzy and operator change.
| /** | ||
| * This hook determine if the first page (page 0) should be fetched. | ||
| * This is because the first page is initially fetched from the Server Side, and injected in the cache (for Performance and SEO). | ||
| * So this hook checks if the first page should be fetched again in the Client Side | ||
| * after 5 minutes since the build time (last fetch from Server Side) or the last fetched time from the ClientSide. | ||
| * | ||
| * @param page The page number | ||
| * @param generatedBuildTime The time the page was generated | ||
| * @returns boolean | ||
| * | ||
| **/ |
| const hasSameVariables = deepEquals( | ||
| pagesCache.current[page], | ||
| getKey(localizedVariables) | ||
| ) |
There was a problem hiding this comment.
question: @eduardoformiga do you have metrics for both comparison strategies that favor deepEquals here?
There was a problem hiding this comment.
🎗️ suggestion: This is one of the cases Biome didn't ignore the automatic lint and fix, please rebase with main to solve it.
There was a problem hiding this comment.
After some fight, now it worked. hahaha
@lucasfp13 I don't have metrics, but deepEquals is less error-prone than |
cf61cc9 to
61264f5
Compare
61264f5 to
75bcd62
Compare
| sort = 'score_desc', | ||
| term = '', | ||
| selectedFacets = [], | ||
| sponsoredCount = 3, |
There was a problem hiding this comment.
question: why is the default 3?
There was a problem hiding this comment.
That's the default value for sponsored products. I remember that I asked somewhere to the team about this value, and they answered that this is the default value.
There was a problem hiding this comment.
oh, I think I was the one who said that! 🙈 The team actually said that 3 was the default value.
| doNotRun: !shouldFetch, | ||
| }) | ||
|
|
||
| const shouldUpdatePages = !hasSameVariables && data !== null |
There was a problem hiding this comment.
question: why is !hasSameVariables not necessary anymore?
There was a problem hiding this comment.
It's more secure to update the cache every time we fetch it from the Client side to keep the most updated value, especially for the first page (page 0). Imagine that the last fetch from the build time occurred 1 day ago, and we now fetch the data with the same variables on the Client Side. In this scenario, although the variables are the same (cache key), the result could change from the IS/Catalog.
Hypothetical scenario: I don't think the cache mechanism would keep the values for much time (the garbage collector will clean them previously).
Co-authored-by: Larícia Mota <[email protected]>
Co-authored-by: Larícia Mota <[email protected]>
Co-authored-by: Larícia Mota <[email protected]>
Co-authored-by: Larícia Mota <[email protected]>
| @@ -0,0 +1,60 @@ | |||
| import { useRef } from 'react' | |||
|
|
|||
| const FIVE_MINUTES = 5 * 60 * 1000 | |||
There was a problem hiding this comment.
question: sorry, I might have missed it, but why 5 minutes? 👀
There was a problem hiding this comment.
Some good reasons:
- Balance between update and performance
- Latency reduction
- Best practice for quasi-dynamic data
- Minimizes impact of temporary failures
- Control over revalidation


What's the purpose of this pull request?
This PR aims to fetch the first page from the PLPs using the server side. This can improve SEO and performance.
It uses the same variables that are used in the first fetch from the client side. If the values have changed 5 minutes from the build or from the latest fetch of the first page, we refetch the first page and update the values.
It also improves:
How to test it?
You can run locally:
I recommend to set the cache to 1 minute to test the requests from PLP here:
faststore/packages/core/src/sdk/product/useShouldFetchFirstPage.ts
Line 3 in 47fd98e
you can also test it in the preview link:
https://starter-7w8gjvlea-vtex.vercel.app/office
Observe the requests from the PLP:
just 1 request to
http://localhost:3000/api/graphql?operationName=ClientProductGalleryQuery
since we don't refetch to include fuzzy and operator params.
there is no current page request to
http://localhost:3000/api/graphql?operationName=ClientManyProductsQuery
since this was moved to the Server Side.
After 5 minutes from build/last client side request, you can see the current page request Client Side that will refresh the data.
http://localhost:3000/api/graphql?operationName=ClientManyProductsQuery
Observe the URL params from the PLPs with fuzzy, operator and all other facets/params.
Test the navigation history in the story.
Test the Search page as well, since changes from PLP components can effect Search page as well.
Starters Deploy Preview
PR
Preview:
https://starter-mrmhyx2h3-vtex.vercel.app/office