[Example #2] Fetch Data On Props Change

by redneckz

HTML

<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/rxjs/bundles/rxjs.umd.min.js"></script>
<script src="https://unpkg.com/@redneckz/react-rxjs@0.0.4/dist/index.min.js"></script>

CSS

.post__title {
    font-size: large;
    font-weight: bold;
}

Babel + JSX

const { map, distinctUntilChanged, switchMap } = rxjs.operators;
const { reactive } = ReactRxjs;

const Posts = reactive(
  props$ => props$.pipe(
    map(({ userId }) => userId),
    distinctUntilChanged(),
    switchMap(fetchPostsByUser),
    map(posts => ({ posts }))
  )
)(
  ({ posts = [] }) => (
    <section>
      {posts.map(({ id, title, body }) => (
        <Post key={id} title={title}>{body}</Post>
      ))}
    </section>
  )
);

function Post({ title, children }) {
  return (
    <article>
      <header className="post__title">{title}</header>
      <p>{children}</p>
    </article>
  );
}

async function fetchPostsByUser(userId) {
  const response = await fetch(
  	`https://jsonplaceholder.typicode.com/posts?userId=${userId}`
  );
  return response.json();
}

ReactDOM.render(<Posts userId={1} />, document.body);