Skip to content

Instantly share code, notes, and snippets.

@stretchkennedy stretchkennedy/connect.js

Last active Jul 26, 2017
Embed
What would you like to do?
react state management idea
const schema = {
view: {
selectedUser: null
},
data: {
users: {
$id: ({ id }, state, path) => fetch(`/api/users/${id}`).then(res => res.json())
}
}
};
export default connectFromSchema(schema);
import { MagicObject } from 'state-magic';
const User = MagicObject({
resolve: ({ id }) => fetch(`/api/users/${id}`).then(res => res.json()),
mutate: ({ id }, body, context) => {
return fetch(`/api/users/${id}`, { method: 'POST', body })
.then(res => res.json())
.then((user) => {
context.store.invalidate('data.friends');
return user;
});
},
});
const schema = {
view: {
selectedUser: null
},
data: {
friends: MagicList({
references: 'data.users.$id',
resolve: () => fetch(`/api/friends`).then(res => res.json()).then(json => json.items),
}),
users: {
$id: User,
}
}
};
export default connectFromSchema(schema);
import connect from './connect';
import React from 'react';
const UserComponent = ({ id, user, selectedUser }) => {
if (user.loading) {
return <span>Loading...</span>;
}
return (
<span
className={selectedUser.value === id ? 'user--selected' : 'user--unselected'}
onClick={() => selectedUser.set(id)}
>
{user.value.name}
</span>
);
};
export default connect(props => ({
user: `data.users.${props.id}`,
selectedUser: 'view.selectedUser'
}))(UserComponent);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.