Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Respond to prop changes with side effect #98

Copy link
Copy link
@OliverJAsh

Description

@OliverJAsh
Issue body actions

Sometimes we want to use an observable not to create state but rather just to perform side effects.

This is possible using useObservable:

import React from 'react';
import { EMPTY } from 'rxjs';
import { useObservable } from 'rxjs-hooks';
import { map, mergeMapTo, tap } from 'rxjs/operators';

declare const sideEffect: (number: number) => void;

const MyComponent: React.FC<{ foo: number }> = props => {
  useObservable(
    input$ =>
      input$.pipe(
        map(([foo]) => foo),
        tap(sideEffect),
        mergeMapTo(EMPTY),
      ),
    props.foo,
    [props.foo],
  );

  return <div>Hello, World!</div>;
};

… but it's a bit awkward for a few reasons:

  • We are forced to return an Observable of a certain type (State), when the type doesn't matter to us, since the result is not being used outside of the hook. We need to do mergeMapTo(EMPTY) at the end of the chain, to satisfy the return type.
  • We are forced to provide an initial state, but again we are not using State here.

What do you think about another hook which is specifically designed for this use case, to avoid the problems above?

useObservableSideEffect(
  input$ =>
    input$.pipe(
      map(([foo]) => foo),
      tap(sideEffect),
    ),
  [props.foo],
);

I'm sure we can find a better name… 😄

samijaber, karol-majewski and zry656565

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.