node package manager
Easy collaboration. Discover, share, and reuse code in your team. Create a free org »

react-coroutine

react-coroutine

npm install react-coroutine

Coroutines are computer program components that generalize subroutines for nonpreemptive multitasking, by allowing multiple entry points for suspending and resuming execution at certain locations. Coroutines are well-suited for implementing more familiar program components such as cooperative tasks, exceptions, event loop, iterators, infinite lists and pipes.
Wikipedia

Use async functions and generators to render React components based on async state.

import React from 'react';
import Coroutine from 'react-coroutine';
async function UserListContainer() {
  try {
    // Wait for async data and render it in the same way as plain components 
    const users = await Users.retrieve();
    return <UserList users={users} />;
  } catch (error) {
    // Handle failures in place with just JavaScript tools 
    return <ErrorMessage error={error} />;
  }
}
 
export default Coroutine.create(UserListContainer);
async function* PokemonInfoPage({ pokemonId, pokemonName }) {
  // Use generators to provide multiple render points of your async component 
  yield <p>Loading {pokemonName} info...</p>;
 
  // Easily import components asynchronously and render them on demand 
  const { default: PokemonInfo } = await import('./PokemonInfo.react');
  const data = await PokemonAPI.retrieve(pokemonId);
 
  return <PokemonInfo data={data} />;
}
 
export default Coroutine.create(PokemonInfoPage);
class MyComponent extends Coroutine {
  async observe() {
    try {
      const users = await Users.retrieve();
      return { status: 'success', users };
    } catch (error) {
      return { status: 'failure', error };
    }
  }
 
  render() {
    switch (this.state.data.status) {
    case 'success':
      return <UserList users={this.state.data.users} />;
    case 'failure':
      return <ErrorMessage error={this.state.data.error} />;
    default:
      return <Loading />;
    }
  }
}

Usage

See details page for more.

List of projects that can be built with react-coroutine

React Coroutine attempts to use basic language features for the sake of solving problems that are usually solved with APIs and new abstractions that require particular knowledge about them and sometimes about internal processes (leaky abstractions).