Skip to content

Instantly share code, notes, and snippets.

@fernandocamargo
Created March 7, 2019 14:41
Show Gist options
  • Save fernandocamargo/4612dc8ff12d48f8cd79603125639fd2 to your computer and use it in GitHub Desktop.
Save fernandocamargo/4612dc8ff12d48f8cd79603125639fd2 to your computer and use it in GitHub Desktop.
import last from "lodash/last";
import React, { Fragment } from "react";
import { usePersisted, useVolatile, useLog } from "nodh";
// your service (async operation)
const fetchGithubRepos = () =>
window
.fetch("https://api.github.com/search/repositories?q=react")
.then(response => response.json());
// your reducers
const newAttempt = () => ({ attempts, ...state }) => ({
...state,
attempts: attempts + 1
});
const setRepos = repos => state => ({ ...state, repos });
// your actions
const actions = ({ persisted, volatile, request }) => ({
getRepos: () =>
fetchGithubRepos()
.then(({ items }) => {
volatile.save(setRepos(items));
request.success("You could grab some response from your request");
})
.catch(({ message }) => request.fail(message))
.finally(() => persisted.save(newAttempt()))
});
// your selector for persisted data
// (similar to Redux's mapStateToProps)
const selector = ({ attempts }) => ({ attempts });
const namespace = "your-namespace";
export default () => {
const [{ attempts = 0 }] = usePersisted({ selector });
const [{ repos = [] }, { getRepos }] = useVolatile({ namespace, actions });
const { repeat, loading, error, success } = last(useLog(getRepos));
return (
<div>
<h1>Attempts: {attempts}</h1>
<button onClick={getRepos} disabled={loading}>
{loading ? "Loading..." : "Click here to fetch repos"}
</button>
{error && (
<div style={{ color: "red" }}>
<h2>{error}</h2>
<button onClick={repeat}>Try again</button>
</div>
)}
{success && <p style={{ color: "green" }}>{success}</p>}
<pre>{JSON.stringify(repos, null, 2)}</pre>
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment