use context in Qwik

127 views Asked by At

I utilize context in Qwik in the following manner.

import {
    component$,
    Slot,
    useContextProvider,
    useStore,
} from '@builder.io/qwik'
import { AppContext } from 'Base'

const AppContextProvider = component$(() => {
    const app = useStore({
        Qwik: "Qwik context is ready to use",
    })
    useContextProvider(AppContext, [app])

    return (
        <>
            <Slot />
        </>
    )
})

export default AppContextProvider

I utilize it within my components.

const [app] = useContext(AppContext)

then I can change or add new item in store in components like this

app.compareItemsId=[1,2,3,4]

When I try to access this value in other components, its data type shows as "proxy". Proxy(Array) how can I fix this problem
log from context

1

There are 1 answers

0
7stud On

When I try to access this value in other components, its data type shows as "proxy". Proxy(Array) how can I fix this problem

I'm not seeing the "proxy" output in the following example:

import {
    type Signal, 
    component$, 
    useSignal,
    useContext,
    useStore,
    useContextProvider,
    createContextId,
} from '@builder.io/qwik';

export const DogContext = createContextId<Signal<string>>(
    'myapp-dog-context'
);

export const CatContext = createContextId<string[]>(
    'app-cat-context' 
);

export default component$( () => {

    const dog = useSignal('golden retriever');
    useContextProvider(DogContext, dog);
    
    const cat = useStore(["black", "calico", "siamese"]);
    useContextProvider(CatContext, cat);
    
    return (
        <>
            <button onClick$={() => 
                    (dog.value = dog.value == 'golden retriever' ? 'poodle' : 'golden retriever')
                }
            >

                Change dog
            </button>
            <Puppy />

            <hr />

            <button onClick$={() => 
                    (cat[0] == 'calico' ? cat[0] = 'black': cat[0] = 'calico')
                }
            >
                Change cat
            </button>
            <Kitten />
        </>
    
    );
});

const Puppy = component$( () => {
    const dog = useContext(DogContext);
    console.log(`dog type: ${typeof dog}`);
    console.log(`dog.value type: ${typeof dog.value}`);

    return <div>My parent is a: {dog.value}</div>;
});

const Kitten = component$( () => {
    const cat = useContext(CatContext);
    console.log(`cat type: ${typeof cat}`);
    
    return <div>The current cat is: {cat[0]}</div>;
});

Here's the output in the server window:

dog type: object
dog.value type: string
cat type: object