Skip to content

Instantly share code, notes, and snippets.

@JonAbrams
Last active July 23, 2018 01:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonAbrams/2bd80a23bbf81b880f7eaace3f2936a4 to your computer and use it in GitHub Desktop.
Save JonAbrams/2bd80a23bbf81b880f7eaace3f2936a4 to your computer and use it in GitHub Desktop.
import { fetchPizza } from '../apiCalls';
/*
handleSubmit is a custom action.
The first parameter is provided by SpaceAce.
The remaining parameters are passed-through
which in this case consists of React's event object
*/
const handleSubmit = async ({ space, merge }, event) => {
event.preventDefault();
// merge does a shallow merge, allowing the assignment of multiple properties at once
merge({ saving: true }); // updates space immediately, triggers re-render
const { data, error } = await fetchPizza({ name: space.name });
if (error) return merge({ error: errorMsg, saving: false });
merge({
saving: false,
pizza: data.pizza // 'Pepperoni', hopefully
});
};
/*
handleReset is another custom action.
This one erases all properties on the space,
replacing them with only the specified ones.
*/
const handleReset = ({ replace }) => {
replace({
name: '',
pizzaLover: false
});
};
export const PizzaForm = ({ space }) => (
<form onSubmit={space(handleSubmit)}>
{/* ... some input elements */}
<p className="error">{space.errorMsg}</p>
{space.pizza && <p>You’ve been given: {space.pizza}</p>}
<button disabled={space.saving} type="submit">Get Pizza</button>
<button disabled={space.saving} type="button" onClick={space(handleReset)}>Reset</button>
</form>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment