Carousel
Carousel¶
Three related reactive fields—selected index, fruit name, and first
letter—updated together when you call rotate. Shows how the backend
can keep a small graph of state consistent in one action.
Backend¶
from rxdjango import ContextChannel, rx, action
class CarouselChannel(ContextChannel):
FRUITS = ['banana', 'apple', 'orange']
selected = rx[int](0)
fruit = rx[str](FRUITS[selected])
first_letter = rx[str](fruit[0])
@action
async def rotate(self):
self.selected = (self.selected + 1) % len(self.FRUITS)
self.fruit = self.FRUITS[self.selected]
self.first_letter = self.fruit[0]
Frontend¶
import React from 'react';
import { useChannel } from '@rxdjango/react';
import { CarouselChannel } from '../../rx/carousel/carousel.channels';
import { Demo, Fields, Field, Button } from '../../components/demo';
export function CarouselDemo() {
const channel = useChannel(CarouselChannel);
return (
<Demo>
<Fields>
<Field label="Selected">
{channel.selected}
</Field>
<Field label="Fruit">
{channel.fruit}
</Field>
<Field label="First letter">
{channel.first_letter}
</Field>
</Fields>
<Button onClick={channel.rotate}>
Next
</Button>
</Demo>
);
}
export default CarouselDemo;