Skip to content

Instantly share code, notes, and snippets.

@shlomokraus
Last active November 24, 2018 17:46
Show Gist options
  • Select an option

  • Save shlomokraus/c0b5b16e72c939feb3a1071ff407fd2c to your computer and use it in GitHub Desktop.

Select an option

Save shlomokraus/c0b5b16e72c939feb3a1071ff407fd2c to your computer and use it in GitHub Desktop.
Redux workflow
/**
* Create redux container
*/
function mapDispatchToProps(dispatch) {
return bindActionCreators(
{
fetchSongs: SongActions.fetchAll,
onDownload: SongActions.download
},
dispatch
);
}
function mapStateToProps(state, ownProps) {
return {
songs: state.songs,
currentlyDownloadingId: state.currentlyDownloadingId
};
}
const SongsPageContainer = Component =>
connect(mapStateToProps, mapDispatchToProps)(Component);
/**
* Create app component that binds the container to the page
*/
const WrappedSongsPage = SongsPageContainer(SongsPage);
function SongsApp() {
return <WrappedSongsPage />;
}
/**
* Page component with all props
*/
interface ISongsPageProps {
fetchSongs: () => void;
onDownload: (id: string) => void;
songs: any[];
currentlyDownloadingId: string;
}
class SongsPage extends React.Component<ISongsPageProps, void> {
componentDidMount() {
this.props.fetchSongs();
}
render() {
return (
<div className="songs-page">
<div className="title">Hooked On Songs</div>
<SongList
songs={this.props.songs}
onDownload={this.props.onDownload}
currentlyDownloadingId={this.props.currentlyDownloadingId}
/>
</div>
);
}
}
/**
* List component with pass-through props for children
*/
function SongList({ songs, onDownload, currentlyDownloadingId }) {
return (
<ul>
{songs.map(song => {
const isDownloading = currentlyDownloadingId === song.id;
const onDownloadClick = () => onDownload(song.id);
return (
<li key={song.id}>
<SongItem
song={song}
onDownload={onDownloadClick}
isDownloading={isDownloading}
/></li>
);
})}
</ul>
);
}
/**
* Song item with download indicator
*/
function SongItem({ song, isDownloading, onDownload }) {
return (
<div className="song-item">
<div className="song-title">{song.title}</div>
<div className="download">
{isDownloading ? (
"Downloading..."
) : (
<div onClick={onDownload}>Download</div>
)}
</div>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment