Skip to content

Instantly share code, notes, and snippets.

View martinseanhunt's full-sized avatar
👌
200

Martin Hunt martinseanhunt

👌
200
View GitHub Profile
@martinseanhunt
martinseanhunt / RefactoringTest.js
Last active April 1, 2022 09:52
Needs refactoring
const App = () => {
const [userId, setUserId] = useState(null);
return (
<div>
<header>
<AppBar
userId={userId}
onLogin={userId => setUserId(userId)}
onLogout={() => setUserId(null)}
{
"name": "MartyPool",
"description": "This is a test pool",
"ticker": "MARTY",
"homepage": "https://teststakepool.com"
}
{
"name": "MartyPool",
"description": "This is a test pool",
"ticker": "MARTY",
"homepage": "https://teststakepool.com"
}
import gql from 'graphql-tag'
import { PER_PAGE } from '../config/config'
const GET_LIST_ITEMS_QUERY = gql`
query GET_LIST_ITEMS_QUERY($skip: Int = 0, $first: Int = ${PER_PAGE}) {
listItems(skip: $skip, first: $first) {
id
title
}
class ListItems extends Component {
onUpdate = cache => {
// Call our helper function to delete item from cache
deleteListItemsFromCache(cache)
// Deleting the item in this way doesn't trigger a re
// render of our Index.js component so we have to call
// refetch which is given to us by our Query component
// and passed down from Index.js via props
this.props.refetch()
class Index extends Component {
render() {
return (
<Query
query={GET_LIST_ITEMS_QUERY}
variables={{
skip: ((this.props.router.query.page || 1) - 1) * perPage
}}
// adding this so we can get the correct loading status on refetch
<Mutation
mutation={CREATE_LIST_ITEM}
variables={{ title: this.state.title }}
// Refetch pagination data on creating an item to update item
// & page counts. The Query is being imported from ./Pagination
refetchQueries={[{ query: LIST_ITEMS_CONNECTION_QUERY }]}
// Call our helper function on update (it will be passed the chache)
update={deleteListItemsFromCache}
@martinseanhunt
martinseanhunt / deleteListItemsFromCache.js
Created October 23, 2018 00:52
A helper function to delete paginated data from the Apollo cache
export default cache => {
// Loop through all the data in our cache
// And delete any items that start with "ListItem"
// This empties the cache of all of our list items and
// forces a refetch of the data.
Object.keys(cache.data.data).forEach(key =>
key.match(/^ListItem/) && cache.data.delete(key)
)
}
@martinseanhunt
martinseanhunt / ListItems(updatefunction).js
Last active October 22, 2018 22:27
Updating the local cache on delete
update = async (cache, payload) => {
// This function fires once the DELETE_LIST_ITEM_MUTATION is complete
// Get the skip value for the current page so we can read the relevant
// query from our cache. I've passed down page from Index.js and imported
// perPage from our config file
const queryVars = { skip: (this.props.page - 1) * PER_PAGE }
// read cache for the page we need to change, GET_LIST_ITEMS_QUERY
// imported from Index.js