Skip to content

Commit

Permalink
feature(core): Allow useContext in same elem as provider
Browse files Browse the repository at this point in the history
  • Loading branch information
wmertens committed Oct 2, 2023
1 parent 716812e commit 38b6b14
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 20 deletions.
18 changes: 18 additions & 0 deletions packages/qwik/src/core/render/ssr/render-ssr.unit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1001,6 +1001,15 @@ renderSSRSuite('component useContextProvider()', async () => {
);
});

renderSSRSuite('component useContextProvider() + useContext()', async () => {
await testSSR(
<ContextWithValueAndUse value="hello bye" />,
`<html q:container="paused" q:version="dev" q:render="ssr-dev" q:manifest-hash="test">
<!--qv q:id=0 q:key=sX:-->hello bye<!--/qv-->
</html>`
);
});

renderSSRSuite('component slotted context', async () => {
await testSSR(
<body>
Expand Down Expand Up @@ -1734,6 +1743,15 @@ export const ContextWithValue = component$((props: { value: string }) => {
);
});

export const ContextWithValueAndUse = component$((props: { value: string }) => {
const value = {
value: props.value,
};
useContextProvider(CTX_VALUE, value);
const ctx = useContext(CTX_VALUE);
return <>{ctx.value}</>;
});

export const Context = component$(() => {
useContextProvider(CTX_INTERNAL, {
value: 'hello',
Expand Down
36 changes: 16 additions & 20 deletions packages/qwik/src/core/use/use-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -322,30 +322,26 @@ export const resolveContext = <STATE extends object>(
containerState: ContainerState
): STATE | undefined => {
const contextID = context.id;
if (hostCtx) {
let hostElement: QwikElement = hostCtx.$element$;
let ctx = hostCtx.$slotParent$ ?? hostCtx.$parent$;
while (ctx) {
hostElement = ctx.$element$;
if (ctx.$contexts$) {
const found = ctx.$contexts$.get(contextID);
if (found) {
return found;
}
if (ctx.$contexts$.get('_') === true) {
break;
}
if (!hostCtx) {
return;
}
let hostElement: QwikElement;
let ctx: QContext | null = hostCtx;
while (ctx) {
hostElement = ctx.$element$;
if (ctx.$contexts$) {
const found = ctx.$contexts$.get(contextID);
if (found) {
return found;
}
ctx = ctx.$slotParent$ ?? ctx.$parent$;
}
if ((hostElement as any).closest) {
const value = queryContextFromDom(hostElement, containerState, contextID);
if (value !== undefined) {
return value;
if (ctx.$contexts$.get('_') === true) {
break;
}
}
ctx = ctx.$slotParent$ ?? ctx.$parent$;
}
return undefined;
const value = queryContextFromDom(hostElement!, containerState, contextID);
return value;
};

export const queryContextFromDom = (
Expand Down

0 comments on commit 38b6b14

Please sign in to comment.