0
0
Svelteframework~10 mins

Why context shares data without prop drilling in Svelte - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a context key using Svelte's setContext.

Svelte
import { setContext } from 'svelte';
const key = [1];
setContext(key, 'shared data');
Drag options to blanks, or click blank then click option'
ASymbol('myKey')
Bnew Map()
C'myKey'
D123
Attempts:
3 left
💡 Hint
Common Mistakes
Using a plain string key can cause conflicts if reused.
2fill in blank
medium

Complete the code to get the shared context data in a child component using getContext.

Svelte
import { getContext } from 'svelte';
const key = Symbol('myKey');
const data = [1](key);
Drag options to blanks, or click blank then click option'
AcreateContext
BgetContext
CuseContext
DsetContext
Attempts:
3 left
💡 Hint
Common Mistakes
Using setContext instead of getContext to retrieve data.
3fill in blank
hard

Fix the error in the code to share data without prop drilling by correctly setting and getting context.

Svelte
/* Parent.svelte */
import { setContext } from 'svelte';
const key = Symbol('myKey');
let sharedData = 'shared data';
setContext(key, [1]);

/* Child.svelte */
import { getContext } from 'svelte';
const key = Symbol('myKey');
const data = getContext(key);
Drag options to blanks, or click blank then click option'
Anull
B42
C'shared data'
DsharedData
Attempts:
3 left
💡 Hint
Common Mistakes
Setting context with a string literal instead of a variable.
4fill in blank
hard

Fill both blanks to create and use context to share a count value without prop drilling.

Svelte
import { setContext, getContext } from 'svelte';

/* Parent.svelte */
const key = [1];
setContext(key, 10);

/* Child.svelte */
const count = [2](key);
Drag options to blanks, or click blank then click option'
ASymbol('countKey')
BgetContext
CsetContext
D'countKey'
Attempts:
3 left
💡 Hint
Common Mistakes
Using string keys that can collide.
Using setContext to get data.
5fill in blank
hard

Fill all three blanks to share a reactive store via context and access it in a child component.

Svelte
import { writable } from 'svelte/store';
import { setContext, getContext } from 'svelte';

const key = [1];
const count = [2](0);
setContext(key, count);

// In child component
const countStore = [3](key);
Drag options to blanks, or click blank then click option'
ASymbol('storeKey')
Bwritable
CgetContext
Dreadable
Attempts:
3 left
💡 Hint
Common Mistakes
Using readable instead of writable for a store that changes.
Not using getContext to access the store.