apollo beginner: cannot read data back from cache - apollo

I have this code to control a search field's value
const GET_SHOP_FILTER = gql`
query getFilter {
name #client
}
`;
class ShopSuggestBox extends Component {
render() {
return (
<div>
<div className="name">
<Query query={GET_SHOP_FILTER}>
{({data, client}) => (
<div>
data is {JSON.stringify(data)}
<input
onChange={e => {
client.writeData({data: {name: e.target.value}})
}} ...//not relevant
My issue is that I get these errors:
[GraphQL error]: Message: Cannot query field "name" on type "Query"., Location: [object Object], Path: undefined
index.js:63 [GraphQL error]: Message: Unknown directive "client"., Location: [object Object], Path: undefined
My understanding is that the directive #client is not interpreted. What did I miss please?

Ok
The issue is that even though the doc says resolvers is not required, you must provide an empty resolver to have it work.
I modified the code as following (so the doc is wrong)
const client = new ApolloClient({
//uri: "http://localhost:4000/graphql"
// cache,
clientState: {
defaults: {
name: "my",
city: "",
selectedId: null,
previewId: null,
selectedComplaintId: null,
}, resolvers: {}
}
});

Related

Next js with django api rendering data

I am working on a front end of a project and I am stuck for a while.
I have created an api with django rest framework and I am trying to connect to a Nextjs front end. The data is to show on the front page that is why I call getInitialProps. Following is the code
import styles from '../styles/Home.module.css';
import axios from 'axios';
const Home = ({ listings, error }) => {
if (error) {
return <div>An error occured: {error.message}</div>;
}
return (
<ul>
{listings.map((listing) => (
<li key={listing.address}>{listing.title}</li>
))}
</ul>
);
};
Home.getInitialProps = async (ctx) => {
try {
const res = await axios.get('http://127.0.0.1:8000/api/listings/?page=4');
const rep = await res.data;
console.log(rep.results);
listings = rep.results;
return { listings };
} catch (error) {
return { error };
}
};
export default Home;
In the console log I get the data, which is in the bellow format:
[
{
index: 1734112,
user: 11233,
title: 'Classical style',
address: 'address 23, city , country',
bedrooms: '2',
bethrooms: '1',
price: '5803',
list_type: 'rent'
},
{
index: 1722303,
user: 32119,
title: 'Pangrati On the Lake',
address: 'address 28, city , country',
bedrooms: '1',
bethrooms: '1',
price: '4800',
list_type: 'rent'
}
]
But I get an error occured in the browser without specifying the error.
And in the console I get the bellow.
next-dev.js?3515:32 Warning: Did not expect server HTML to contain the text node "listings is not defined" in <div>.
at div
at Home (webpack-internal:///./pages/index.js:50:26)
at MyApp (webpack-internal:///./pages/_app.js:38:27)
at ErrorBoundary (webpack-internal:///./node_modules/next/dist/compiled/#next/react-dev-overlay/client.js:8:20584)
at ReactDevOverlay (webpack-internal:///./node_modules/next/dist/compiled/#next/react-dev-overlay/client.js:8:23125)
at Container (webpack-internal:///./node_modules/next/dist/client/index.js:359:9)
at AppContainer (webpack-internal:///./node_modules/next/dist/client/index.js:793:26)
at Root (webpack-internal:///./node_modules/next/dist/client/index.js:915:27)
I am not sure what the issue is so any help much appreciated. Thank you!
You are assigning value to some variable listings = rep.results;, but this variable was not declared, you can't do that in strict mode (which I believe is default in that case)
So just declare it as const and the error should go away:
const listings = rep.results

Not working json data in Template with vue js

I can not pass the json data in the template correctly. I try in any way I can not find. If you want everything in a snippet I can put it. Thank you in advance.
My HTML:
<div id="app">
<cols :pops="pops"></cols>
</div>
My App:
var main = new Vue({
el: '#app',
data:{
pops: [],
},
mounted: function () {
var self = this;
$.ajax({
url: '../assets/data/pop.json',
method: 'GET',
success: function (data) {
self.pops = data;
},
error: function (error) {
console.log(error);
}
});
},
In same file (app)
Vue.component('cols', {
template:
`<li v-for="pop in pops"> <b>{{ pop.Commune }}</b><span>{{ pop.Population }}</span><div :style="{width: ( pop.Population/520504 * 100) + '%'}"></div></li>`,
});
ERROR
Property or method "pops" is not defined on the instance but referenced during render.
The "data" option should be a function that returns a per-instance value in component definitions.
You're not actually passing the data properties to the component (and the others).
In your HTML try to do this:
<div id="app">
<headermain></headermain>
<search></search>
<cols :pops="pops"></cols>
</div>
Injecting the data.pops in the pops property of the cols component.

Querying with apollo-link-state gives the error "Field <name> doesn't exist on type 'Query'"

I'm totally new to both Apollo and GraphQL. I'm following along with this apollo-link-state-tutorial, and am hitting a stumbling block.
I have set up my link with a currentGame property default.
const stateLink = withClientState({
cache: stateCache,
defaults: {
currentGame: {
__typename: 'currentGame',
teamAScore: 0
}
}
})
I'm using it in my client.
const client = new ApolloClient({
stateCache,
link: stateLink,
...
})
I'm defining a GraphQL query like this:
const getCurrentGame = gql`
query {
currentGame #client {
teamAScore
}
}
`
I am connecting it to my component's props.
export default compose(
graphql(getCurrentGame, {
props: ({ data: { currentGame }}) => ({
currentGame
})
})
)
This generates an error in the console.
[GraphQL error]: Message: Field 'currentGame' doesn't exist on type 'Query', Location: [object Object], Path: undefined
I've gone over my code and haven't been able to spot what is surely a typo or simple mistake. How can I debug this error message, or what does it suggest the problem is?
Update: I have tried adding a resolver as suggested by Tal Z, but am still receiving the same error message.
const stateCache = new InMemoryCache()
const stateLink = withClientState({
cache: stateCache,
resolvers: {
Query: {
currentGame: () => {
return {}
}
}
},
defaults: defaultState
})
For what it's worth, most of the few example repositories I've found have queries for fields that do not have resolvers defined. For example, this queries for todo list items, but the only resolver defined is for a mutation.
Well, I figured it out... this breaks:
import ApolloClient from 'apollo-boost'
This works:
import ApolloClient from 'apollo-client'
I have no idea what the difference is.

Loading Remote Data using Select2 and Webservice

I am using Select2 4.0.3 in my web forms .net application. I am trying to Load Remote data using a webservice, but its not working as expected.
First Issue am facing is that the webservice method is not getting called and am getting a console error:
System.InvalidOperationException: Missing parameter: text.
at System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection)
at System.Web.Services.Protocols.HtmlFormParameterReader.Read(HttpRequest request)
at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
So I tried removing the paremeter from the webservice call
<WebMethod()> _
Public Function GetDataFromService() As String
Doing this the method got fired, but still the items in the select2 did not get populated (screenshot atached).
Can someone help me to figure out where am I making a mistake.
Here are the details:
Select2 Code in the Webform:
$("#ddlEntity").select2({
ajax: {
url: "Service/InvoiceHTMLService.asmx/GetDataFromService",
type: 'POST',
delay: 250,
params: {
contentType: 'application/json; charset=utf-8'
},
dataType: 'json',
data: function (term, page) {
return {
text: term,
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
WebService Method:
<WebMethod()> _
Public Function GetDataFromService(text As String) As String
Return "{['id':1, 'text':'Test1'],['id':2, 'text':'Test2']}"
End Function
Try this please
var fd = new FormData();
fd.append("text",term);
ajax: {
url: "Service/InvoiceHTMLService.asmx/GetDataFromService",
type: 'POST',
delay: 250,
params: {
contentType: 'application/json; charset=utf-8'
},
dataType: 'json',
data: fd
...
I think you did not create template for this select2. since you are using templateResult and templateSelection it requires template or you can remove those two options.
For your reference : https://select2.github.io/examples.html#templating
Updated:
they have changed query callback from
data: function (term, page) {
return {
text: term,
};
},
into
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},

Algolia - Search with a condition to look into an array of string

I am using rails and algolia gem with mongoid datastore.
I am sending data to algolia for a model Question. One of the doc example in Algolia system is
objectID: 5691e056410213a381000000
text: "what is #cool about your name Mr. John? #name #cool"
asked_to: ["565571704102139759000000", "i7683yiq7r8998778346q686", "kjgusa67g87y8e7qtwe87qwe898989"]
asked_by: "564a9b804102132465000000"
created_at: "2016-01-10T04:38:46.201Z"
card_url: "http://localhost:3000/cards/5691e056410213a381000000"
answerers: []
has_answer: false
requestor_count: 0
status: "active"
popularity_point: 0
created_at_i: 1452400726
_tags: ["cool", "name"]
I want to find all those documents, where it meets these two conditions:
1) text contains your name
2) asked_to contains i7683yiq7r8998778346q686
I am using Twitter's typeahead javascript library. And my UI's javascript to implement algolia search is as follows:
<input class="typeahead ui-widget form-control input-md search-box tt-input" id="typeahead-algolia" placeholder="Search questions" spellcheck="false" type="text" autocomplete="off" dir="auto" style="position: relative; vertical-align: top;">
$(document).on('ready page:load', function () {
var client = algoliasearch("APPLICATION_ID", "SEARCH_KEY");
var index = client.initIndex('Question');
$('#typeahead-algolia').typeahead(
{
hint: false,
highlight: true,
minLength: 1
},
{
source: index.ttAdapter({hitsPerPage: 10}),
displayKey: 'text'
}
).on('keyup', this, function (event) {
if (event.keyCode == 13) {
$('#typeahead-algolia').typeahead('close');
window.location.href = "/?keyword="+encodeURIComponent($('#typeahead-algolia').val());
}
});
$('.typeahead').bind('typeahead:select', function(ev, suggestion) {
window.location.href = suggestion.card_url;
});
});
So my question is:
This code works perfectly. But how to add condition for asked_to contains i7683yiq7r8998778346q686 in above javascript to filter out result.
You can use a facet filter on the asked_to attribute in your query.
You first need to declare the attribute asked_to as an attribute for faceting in your index settings and then pass asked_to:i7683yiq7r8998778346q686 as a facet filter in your query via the facetFiltersquery parameter.
When your index settings are changed, you can change your source to add the facetFilters parameter:
$('#typeahead-algolia').typeahead(
{
hint: false,
highlight: true,
minLength: 1
},
{
source: index.ttAdapter({hitsPerPage: 10, facetFilters: "asked_to:i7683yiq7r8998778346q686"}),
displayKey: 'text'
}
).on('keyup', this, function (event) {
if (event.keyCode == 13) {
$('#typeahead-algolia').typeahead('close');
window.location.href = "/?keyword="+encodeURIComponent($('#typeahead-algolia').val());
}
});