Skip to content

Instantly share code, notes, and snippets.

@hamidabdulmalik
Forked from n1ru4l/ArtistList.js
Created August 15, 2017 11:05
Show Gist options
  • Save hamidabdulmalik/e04f88bef5e879231ca3b8ebf5a42ab1 to your computer and use it in GitHub Desktop.
Save hamidabdulmalik/e04f88bef5e879231ca3b8ebf5a42ab1 to your computer and use it in GitHub Desktop.
mobx + apollo-client + react
import React from 'react'
import { observer } from 'mobx-react'
function ArtistList({ uiState: { artistData } }) {
const { data } = artistData;
if ( !data || !data.artists || !data.artists.length ) {
return <div>No artists bruh.</div>
}
const { artists } = data
return (
<ul>
{artists.map(artist =>
<li key={artist.id}>{artist.name}</li>
)}
</ul>
)
}
export default observer(ArtistList)
import createQueryObservable from './createQueryObservable'
const ARTISTS_QUERY = gql`
query artists {
artists {
id
name
}
}
`
export default createQueryObservable({ query: ARTISTS_QUERY})
import ApolloClient, { createNetworkInterface } from 'apollo-client'
const networkInterface = createNetworkInterface({ uri: '/graphql' })
const dataIdFromObject = (result) => {
if (result.id && result.__typename) {
return result.__typename + result.id;
}
return null;
}
const client = new ApolloClient({
networkInterface,
dataIdFromObject,
})
export default client
import client from './client'
import { observable, action } from 'mobx'
export default function createQueryObservable({ query = null, variables = {} , ...options}) {
const observableQuery = client.watchQuery({ query, variables, ...options})
const _observable = observable(observableQuery.currentResult())
const applyChanges = action((res) => {
_observable.data = res.data
_observable.loading = res.loading
_observable.networkStatus = res.networkStatus
})
observableQuery.subscribe({
next(result) {
console.log('next', result)
applyChanges(result)
},
error(err) {
console.log('err', err)
}
})
return _observable
}
import React from 'react'
import ReactDOM from 'react-dom'
import { useStrict } from 'mobx'
import ArtistList from './ArtistList'
import uiState from './uiState'
useStrict(true)
ReactDOM.render(
<ArtistList uiState={uiState} />,
document.getElementById('root')
)
import { extendObservable } from 'mobx'
import artists from './artists'
function UiState() {
extendObservable(this, {
get artistData() {
return artists
}
})
}
export default new UiState
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment