rx fields

rx fields

This example shows how an rx field can be used as a bare str or int. They are indeed extensions of int and str.

NOTE: bool type cannot be extended. rx[bool] fields cannot be used with is comparison.

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;