Introducing fetch-component

This is a quite simple React <Fetch /> component that makes AJAX call just a component a way.

npm install --save fetch-component

or

yarn add fetch-component

Usage:

import React from 'react'
import Fetch from 'fetch-component'
function Hello () {
return (
<div>
<h1>Hello from React</h1>
<Fetch url={'https://api.github.com/user/repos'}>
{data => <p>{data.message}</p>}
</Fetch>
</div>
)
}
export default Hello 

data => <p> {data.message} </p> might be weird if you don’t familiar with function as children. Essentially, React’s children is just a props, that is can be bent and used however the component wants to.

Under the hood, it looked like this:

this.props.children(this.state.data)

That’s it! every time the <Fetch /> props.url updates, it will trigger a new request and invoke it’s children with a state that contains the response.

Advanced usage

You can find it in the demo folder

import React from 'react';
import { render } from 'react-dom';
import Fetch from 'fetch-component';
const Box = props => (
<div style={{ float: 'left', width: `${100 / 4}%` }}>
{props.children}
</div>
);
const AsyncList = props => (
<Fetch
onLoading={() => <p>Loading...</p>}
onSuccess={data => (
<ul>
{data.map(post => (
<li key={post.id}>
{post.title}
</li>
))}
</ul>
)}
onError={(error, reload) => (
<div>
<p>
Error!
</p>
<pre>
{error.message}
</pre>
<button onClick={e => reload(props)}>Reload?</button>
</div>
)}
{...props}
/>
);
const Demo = props => (
<div>
<Box>
<h1>onSuccess</h1>
<AsyncList url={'https://jsonplaceholder.typicode.com/posts'} />
</Box>
<Box>
<h1>onError</h1>
<AsyncList
url={'https://jsonplaceholder.typicode.com/poss'}
onError={(error, reload) => (
<div>
<p>
Error!
</p>
<pre>
{error.message}
</pre>
<button
onClick={e =>
reload({
...props,
url: 'https://jsonplaceholder.typicode.com/posts',
})}
>
Reload?
</button>
</div>
)}
/>
</Box>
<Box>
<h1>onLoading</h1>
<AsyncList />
</Box>
<Box>
<h1>With Children</h1>
<AsyncList url={'https://jsonplaceholder.typicode.com/posts'}>
{data => <pre>{JSON.stringify(data, null, 2)}</pre>}
</AsyncList>
</Box>
</div>
);
render(<Demo />, document.querySelector('#demo'));

You can find the repo here

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.