Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/franciscop/pray

React asynchronous components
https://github.com/franciscop/pray

async components javascript react

Last synced: 13 days ago
JSON representation

React asynchronous components

Awesome Lists containing this project

README

        

# Pray [![npm install pray](https://img.shields.io/badge/npm%20install-pray-blue.svg)](https://www.npmjs.com/package/pray) [![gzip size](https://img.badgesize.io/franciscop/pray/master/index.min.js.svg?compression=gzip)](https://github.com/franciscop/pray/blob/master/index.min.js)

React asynchronous components:

```js
// Books.js
import React from 'react';
import pray from 'pray';

// Wrap the async component in pray:
export default pray(async () => {
const books = await fetch('/books').then(res => res.json());

return (


    {books.map(book =>
  • {book.title}
  • )}

)
});
```

Then in your main code import and use it as usual:

```js
// App.js
import React from 'react';
import Books from './Books';

export default () => (

);
```

## Spinner

You can add a spinner for whenever the main component is still loading:

```js
//
const Spinner = () => 'Loading...';

// Note that we pass the component, not the instance:
export default pray(Spinner, async () => {
...
});
```

You can also assign it on render time:

```js
// App.js
const Spinner = () => "Loading...";

// We again pass the component, not the instance:
export default () => (

);
```

## Props

Props will be passed as expected:

```js
// Book.js
export default pray(async ({ id }) => {
const book = await fetch(`/books/${id}`).then(res => res.json());
return

{book.title}
;
});

// App.js
export default () => ;
```

> None of the Hooks can be used within async components. Please call those above and pass them as props:

```js
const Books = pray(async ({ onLoad }) => {
const books = await fetch('/books').then(res => res.json());
onLoad(books);
return (


    {books.map(book =>
  • {book.title}
  • )}

)
});

const BookList = () => {
const [books, setBooks] = useState(null);
return (


Book count: {books.length}
'Loading...'} onLoad={setBooks} />

);
};
```