Added Reactive ContextAPI

pull/7290/head
babakfp 5 years ago
parent 252895d42a
commit 4efc1a7f28

@ -162,6 +162,22 @@ Like lifecycle functions, this must be called during component initialisation.
> Context is not inherently reactive. If you need reactive values in context then you can pass a store into context, which *will* be reactive.
#### Reactive ContextAPI
```
<script>
import { setContext } from 'svelte'
import { writable } from 'svelte/store'
let count = writable(0)
setContext('count', count)
</script>
Count is: {$count}
```
More about [Reactive ContextAPI in the tutorial](https://svelte.dev/tutorial/reactive-contextapi)
#### `getContext`
```js

@ -0,0 +1,8 @@
<script>
import Parent from './Parent.svelte'
import Child from './Child.svelte'
</script>
<Parent>
<Child />
</Parent>

@ -0,0 +1,8 @@
<script>
import { getContext } from 'svelte'
let count = getContext('count')
</script>
<p>Child's count is: {count}</p>
<button on:click={_=> count++}>Add Count</button>

@ -0,0 +1,10 @@
<script>
import { setContext } from 'svelte'
let count = 0
setContext('count', count)
</script>
<p>Parent's count is: {count}</p>
<slot />

@ -0,0 +1,8 @@
<script>
import Parent from './Parent.svelte'
import Child from './Child.svelte'
</script>
<Parent>
<Child />
</Parent>

@ -0,0 +1,8 @@
<script>
import { getContext } from 'svelte'
let count = getContext('count')
</script>
<p>Child's count is: {$count}</p>
<button on:click={_=> $count++}>Add Count</button>

@ -0,0 +1,11 @@
<script>
import { setContext } from 'svelte'
import { writable } from 'svelte/store'
let count = writable(0)
setContext('count', count)
</script>
<p>Parent's count is: {$count}</p>
<slot />

@ -0,0 +1,28 @@
---
title: Reactive ContextAPI
---
Context isn't inherently reactive. If we want reactive values in context then we need to combine it with a store. In this tutorial we are going to create a reactive value with the ContextAPI.
Click on the "Add Count" button. You will see only the child's count will get increased and the parent's count stays the same.
To make it reactive, we need to convert the initial value of the `count` to a readable store.
```HTML
<!-- Parent.svelte -->
<script>
import { writable } from 'svelte/store'
let count = writable(0)
</script>
```
Now we have a writable store called `count`, so we need to use it like `$count` as it's explained in the [writable stores tutorial](https://svelte.dev/tutorial/writable-stores).
```HTML
<!-- Parent.svelte -->
<p>Parent's count is: {$count}</p>
<!-- Child.svelte -->
<p>Child's count is: {$count}</p>
<button on:click={_=> $count++}>Add Count</button>
```
Loading…
Cancel
Save