setContext and getContext functions correctlysetContext and getContext functions correctlyParent.svelte. Inside its <script> tag, declare a variable called message and set it to the string "Hello from Parent".Use let message = "Hello from Parent"; inside the <script> tag.
Parent.svelte, import setContext from "svelte". Then call setContext with the key "sharedMessage" and the value message.Remember to import setContext and call it with the key and message.
Child.svelte. Inside its <script> tag, import getContext from "svelte". Use getContext with the key "sharedMessage" to get the message and store it in a variable called receivedMessage.Use getContext("sharedMessage") and assign it to receivedMessage.
Child.svelte, below the paragraph, add a new paragraph that displays the variable receivedMessage using Svelte's curly braces syntax.Use {receivedMessage} inside a paragraph to show the message.
getContext in Svelte?getContextgetContext is used to access data that a parent component has shared using setContext.
Other options describe unrelated tasks like local state or event listening, which getContext does not do.
getContext takes a string key to retrieve the shared value.
const user = getContext('user'); uses the correct string key syntax. const user = setContext('user'); wrongly uses setContext. const user = getContext(user); passes a variable instead of a string. const user = getContext({ key: 'user' }); passes an object, which is invalid.
setContext('theme', 'dark'), what will the child component log with console.log(getContext('theme'))?The parent sets the key 'theme' with value 'dark'. The child uses getContext with the same key.
Since the keys match, getContext returns 'dark'. Other options are incorrect values or undefined.
const data = getContext();
getContext requires a key argument to specify which context to retrieve.
The snippet calls getContext without any argument, causing an error.
getContext('settings') but only the grandparent used setContext('settings', {mode: 'auto'}), what will the grandchild receive?Context set by any ancestor is accessible by all descendants, not just direct children.
The grandchild can access the 'settings' context set by the grandparent, receiving the object {mode: 'auto'}.
Pass the test and this pattern moves unknown