简体   繁体   中英

Convert observable to jsx component

I have an observable which will give json object at any time. For simplicity let's take below as example

// observable that emits a number after every 1 second
const $dynamic = from([1, 2, 3, 4]).pipe(concatMap(x=>of(x).pipe(delay(1000) )))

I just took an example here, in real $dynamic could get new value any time.

Now what I want is to have a list of jsx component and I want them to update as soon as new entry is pushed in $dynamic

function MyApp() {
    return <>
        <span>1</span>
        <span>2</span>
        <span>3</span>
        <span>4</span>      <!------- Those entries should be loaded dynamically from $dynamic because  new entries could errive in $dynamic -->
    </>
}

So how I can subscribe to $dynamic in such a way that I can have list of elements as shown above and if new entry comes, it should be reflected there.

You can subscribe to the observable in useEffect hook then set new value to local state in next callback. Each time the local state of a component is changed, the rendering of the component is triggered.

import React, { useEffect, useState } from "react";
import { from, of } from "rxjs";
import { concatMap, delay } from "rxjs/operators";

export default function App() {
  const [items, setItems] = useState([]);
  const $dynamic = from([1, 2, 3, 4]).pipe(
    concatMap((x) => of(x).pipe(delay(1000)))
  );

  useEffect(() => {
    $dynamic.subscribe((x) => setItems((pre) => pre.concat([x])));
  }, []);

  return (
    <div className="App">
      {items.map((v, idx) => {
        return <p key={idx}>{v}</p>;
      })}
    </div>
  );
}

CodeSandbox

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM