-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feature/rtkq ssr #1270
Closed
+253
−11
Closed
Feature/rtkq ssr #1270
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -94,4 +94,5 @@ export type Api< | |
TagTypes | NewTagTypes, | ||
Enhancers | ||
> | ||
ssr: Record<string, any> | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
import React from 'react' | ||
import { renderToStaticMarkup } from 'react-dom/server' | ||
|
||
import type { Dispatch } from 'react' | ||
import type { AnyAction, Middleware, Store } from 'redux' | ||
|
||
export async function getDataFromTree( | ||
storeFn: (middleWare: Middleware) => Store, | ||
App: ({ store }: { store: Store }) => JSX.Element, | ||
renderFn = renderToStaticMarkup | ||
) { | ||
const middlewareControls = createQueryMiddleWare() | ||
const store = storeFn(middlewareControls.middleware) | ||
try { | ||
await _getDataFromTree(middlewareControls, () => | ||
renderFn(<App store={store} />) | ||
) | ||
} catch (e) { | ||
console.log(e) | ||
} | ||
|
||
return store | ||
} | ||
|
||
function createQueryMiddleWare() { | ||
let resolve: ((v?: unknown) => void) | null = null | ||
let reject: ((v?: unknown) => void) | null = null | ||
let onQueryStarted: (querySet: Set<String>) => void = () => undefined | ||
|
||
const state = { | ||
pendingQueries: new Set<String>(), | ||
renderComplete: false, | ||
queryStarted: false, | ||
promise: new Promise((res, rej) => { | ||
resolve = res | ||
reject = rej | ||
}), | ||
} | ||
|
||
const timeout = setTimeout(() => { | ||
reject?.() | ||
}, 5000) | ||
|
||
return { | ||
renderStart: () => { | ||
state.queryStarted = false | ||
state.renderComplete = false | ||
}, | ||
renderDone: () => { | ||
state.renderComplete = true | ||
state.promise = new Promise((res, rej) => { | ||
resolve = res | ||
reject = rej | ||
}) | ||
|
||
if (state.pendingQueries.size === 0) { | ||
resolve?.() | ||
} | ||
}, | ||
onQueryStarted: (callback: (querySet?: Set<String>) => void) => { | ||
onQueryStarted = callback | ||
}, | ||
middleware: () => (next: Dispatch<AnyAction>) => (action: AnyAction) => { | ||
const result = next(action) | ||
|
||
if (typeof action.type === 'string') { | ||
if (action.type.endsWith('executeQuery/pending')) { | ||
state.pendingQueries.add(action.meta.requestId) | ||
onQueryStarted(state.pendingQueries) | ||
} else if ( | ||
action.type.endsWith('executeQuery/fulfilled') || | ||
action.type.endsWith('executeQuery/rejected') | ||
) { | ||
state.pendingQueries.delete(action.meta.requestId) | ||
if (state.renderComplete && state.pendingQueries.size === 0) { | ||
clearTimeout(timeout) | ||
resolve?.() | ||
} | ||
} | ||
} | ||
return result | ||
}, | ||
state, | ||
} | ||
} | ||
|
||
async function _getDataFromTree( | ||
middlewareControls: ReturnType<typeof createQueryMiddleWare>, | ||
renderFn: () => void | ||
): Promise<any> { | ||
let queryStarted = false | ||
middlewareControls.onQueryStarted(() => (queryStarted = true)) | ||
middlewareControls.renderStart() | ||
renderFn() | ||
middlewareControls.renderDone() | ||
await middlewareControls.state.promise | ||
|
||
if (queryStarted) { | ||
return _getDataFromTree(middlewareControls, renderFn) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
107 changes: 107 additions & 0 deletions
107
packages/toolkit/src/query/tests/getDataFromTree.test.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,107 @@ | ||
import * as React from 'react' | ||
import { Provider } from 'react-redux' | ||
import { renderToString } from 'react-dom/server' | ||
|
||
import type { ReactNode } from 'react' | ||
import type { Middleware, Store } from 'redux' | ||
|
||
import { createApi, fakeBaseQuery, getDataFromTree } from '../react' | ||
|
||
import { configureStore } from '@internal/configureStore' | ||
|
||
describe('getDataFromTree walks the tree and collects the data in the store', () => { | ||
const testApi = createApi({ | ||
baseQuery: fakeBaseQuery(), | ||
endpoints: (build) => ({ | ||
withQueryFn: build.query({ | ||
queryFn(arg: string) { | ||
return { data: `resultFrom(${arg})` } | ||
}, | ||
}), | ||
}), | ||
ssr: true, | ||
}) | ||
|
||
const storeFn = (middleware: Middleware) => | ||
configureStore({ | ||
reducer: { [testApi.reducerPath]: testApi.reducer }, | ||
middleware: (gDM) => gDM({}).concat([testApi.middleware, middleware]), | ||
}) | ||
|
||
const QueryComponent = ({ | ||
queryString, | ||
children, | ||
}: { | ||
queryString: string | ||
children?: ReactNode | ||
}) => { | ||
const { data } = testApi.useWithQueryFnQuery(queryString) | ||
|
||
if (!data) { | ||
return null | ||
} | ||
|
||
return ( | ||
<div> | ||
{JSON.stringify(data)} | ||
<div>{children}</div> | ||
</div> | ||
) | ||
} | ||
|
||
const TestApp = ({ store }: { store: Store }) => { | ||
return ( | ||
<Provider store={store}> | ||
<QueryComponent queryString="top"> | ||
<QueryComponent queryString="nested" /> | ||
</QueryComponent> | ||
</Provider> | ||
) | ||
} | ||
it('resolves all the data', async () => { | ||
const store = await getDataFromTree(storeFn, TestApp) | ||
|
||
const html = renderToString(<TestApp store={store} />) | ||
|
||
expect(html).toMatchInlineSnapshot( | ||
`"<div>"resultFrom(top)"<div><div>"resultFrom(nested)"<div></div></div></div></div>"` | ||
) | ||
expect(store.getState()).toStrictEqual({ | ||
api: { | ||
config: { | ||
focused: true, | ||
keepUnusedDataFor: 60, | ||
middlewareRegistered: true, | ||
online: true, | ||
reducerPath: 'api', | ||
refetchOnFocus: false, | ||
refetchOnMountOrArgChange: false, | ||
refetchOnReconnect: false, | ||
}, | ||
mutations: {}, | ||
provided: {}, | ||
queries: { | ||
'withQueryFn("nested")': { | ||
data: 'resultFrom(nested)', | ||
endpointName: 'withQueryFn', | ||
fulfilledTimeStamp: expect.any(Number), | ||
originalArgs: 'nested', | ||
requestId: expect.any(String), | ||
startedTimeStamp: expect.any(Number), | ||
status: 'fulfilled', | ||
}, | ||
'withQueryFn("top")': { | ||
data: 'resultFrom(top)', | ||
endpointName: 'withQueryFn', | ||
fulfilledTimeStamp: expect.any(Number), | ||
originalArgs: 'top', | ||
requestId: expect.any(String), | ||
startedTimeStamp: expect.any(Number), | ||
status: 'fulfilled', | ||
}, | ||
}, | ||
subscriptions: expect.any(Object), | ||
}, | ||
}) | ||
}) | ||
}) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just leaving this comment to point out to anyone not used to SSR that this dispatch is the necessary "hack" to make this whole approach work. Since
useEffect
doesn't run on the server, when in ssr mode this PR would make the dispatch fire directly in render instead, breaking the no observable side effects in render rule. The new SSR renderer in React 18 will be pretty likely to break/break with this approach (and indeed any approach that fetches data from within the tree).Because of how SSR works pre React 18, this is pretty much the only way to do it if you want to support fetching data from within the component tree, instead of only ahead of rendering. So while not an uncommon approach, I wanted to clearly mark out the "hacky part" to others. 😄
(I'll leave some more thoughts and comments on the linked issue instead of here on the PR since I think they fit better there. Update: Comment added here)