Apollo client useQuery fails to return cached data when variables are changed - apollo

Consider the following queries
useQuery(POSTS, {
variables: {
offset: currPage * 20
}
})
where currPage is a React local state variable. It will get updated when user paginates
Intended outcome:
When currPage=1, new data is fetched, when currPage=2, new data is fetched... When user paginates to the previous page (page 1), because query with currPage=1 is already fetched, it should just read the cache
Actual outcome:
When user paginates from page 1 to page 2, new data for page 2 is fetched, however, when user paginates back to page 1, cache is not read, data is still displayed for page 2
Versions
Apollo client version: #apollo/client: ^3.0.0-beta.14
This bug is also reported in Apollo client GitHub: https://github.com/apollographql/apollo-client/issues/5659

Related

Instagram Graph API - Fetch media insights metric when a user switched from personal to business account

I'm looking for a way to fetch Media Insights metrics in Instagram Graph API (https://developers.facebook.com/docs/instagram-api/reference/media/insights) with a nested query based on the userId, even when a client switched from a Personal to a Business account.
I use this nested query to fetch all the data I need : https://graph.facebook.com/v3.2/{userId}?fields=followers_count,media{media_type,caption,timestamp,like_count,insights.metric(reach, impressions)} (this part causes the error: insights.metric(reach, impressions) - it works however for an account that has always been a Business one)
However, because some media linked to the userId were posted before the user switched to a Business account, instead of returning the data only for the media posted after, the API returns this error:
{
"error": {
"message": "Invalid parameter",
"type": "OAuthException",
"code": 100,
"error_data": {
"blame_field_specs": [
[
""
]
]
},
"error_subcode": 2108006,
"is_transient": false,
"error_user_title": "Media Posted Before Business Account Conversion",
"error_user_msg": "The media was posted before the most recent time that the user's account was converted to a business account from a personal account.",
"fbtrace_id": "Gs85pUz14JC"
}
}
Is there a way to know, thru the API, which media were created before and after the account switch from Personal to Business? Or is there a way to fetch the date on which the account was switched?
The only way I currently see to get the data I need is to use the /media edge and query insights for each media until I get an error. Then I would get approximately the date I need. However, this is not optimized at all since we are rate limited to 200 calls per user per hour.
I have the same problem.
For now, I'm Switch between queries (if first have error)
"userId"?fields=id,media.limit(100){insights.metric(reach, impressions)}
"userId"?fields=id,media.limit(100)
I show the user all insights in zero.
I don't know if they're the best alternative, like identify the time of conversion to business and get the post between this range of DateTime
I got the same problem and solved it like this:
Use the nested query just like you did, including insights.metric
If the error appears, do another call without insights.metric - to at least get all other data
For most accounts, it works and there is no additional API call. For the rest, i just cannot get the insights and i have to live with it, i guess - until Facebook/IG fixes the issue.
I got the same problem and solved it like this:
Step1: Convert your Instagram account to a Professional account.
Step2: Then According to Error Post a new post on Instagram and get their Post-ID.
Step3: Then try to get a request using that Post-ID.
{Post-ID}?fields=comments_count,like_count,timestamp,insights.metric(reach,impressions)
curl -i -X GET "https://graph.facebook.com/v12.0/{Post-ID}?fields=comments_count%2Clike_count%2Ctimestamp%2Cinsights.metric(reach%2Cimpressions)&access_token={access_token}"
For more: insights
Here is the relevant logic from a script that can handle this error while still doing a full import. It works by reducing the requested limit to 1 once the error is encountered. It will keep requesting insights until it encounters the error again, then removes insights from the fields and returns to the requested limit.
limit = 50
error_2108006 = False
metrics = 'insights.metric%28impressions%29%2C' # Must be URL encoded for replacement
url = '/PAGE_ID/media?fields=%sid,caption,media_url,media_type&limit=%s' % (metrics, limit)
# While we have more pages
while True:
# Make your API call to Instagram
posts = get_posts_from_instagram(url)
# Check for error 2108006
if posts == 2108006:
# First time getting this error, keep trying to get insights but one by one
if error_2108006 is False:
error_2108006 = True
url = url.replace('limit={}'.format(limit), 'limit=1')
continue
# Not the first time. Strip out insights and return to desired limit.
url = url.replace(metrics, '')
url = url.replace('limit=1', 'limit='.format(limit))
continue
# Do something with the data
for post in posts:
continue
# If there are more pages, fetch the next URL
if 'paging' in posts and 'next' in posts['paging']:
url = posts['paging']['next']
continue
# Done
break

How to make API GET requests with no API Public Key

I am trying to extract data from an API but in the documentation I was only given one API key, which I assume is the private key.
If this is the case how do I make a GET call in python to pull out data for say inventory based on below documentation documentation(can not post entire document) and if no URL is provided?:
Public Inventory API
1.0
[ Base url: https://partner-gateway.staging.mjplatform.com/v1] https://partners.mjfreeway.com/docs/inventory
API data related to inventory management
Schemes
catalog
GET
/catalog
Listing of Sellable Products
This request provides a detailed listing of all sellable products, also referred to throughout the system as "item masters", for the active facility. The listing can be filtered by some simple parameters.
Parameters
Name Description
category_id
integer
(query)
The ‘id’ of a single category to which you want to limit results
subcategory_id
integer
(query)
The ‘id’ of a single subcategory to which you want to limit results
strain_id
integer
(query)
The ‘id’ of a single strain to which you want to limit results
item_number
string
(query)
The item number of a particular item master, i.e. BKSA00000003
uom_type
string
(query)
The method of measurement for the item. Valid options are discrete, weight, and volume
available_online
boolean
(query)
A boolean indicator of whether the item can be sold online
This is my code so far:
import requests
# api-endpoint
URL = "https://www.mjplatform.com/catalog"
# location given here
key = "123abc"
# defining a params dict for the parameters to be sent to the API
PARAMS = {URL:key}
# sending get request and saving the response as response object
r = requests.get(url = URL, params = PARAMS)
# extracting data in json format
data = r.json()
When I run the above I get the following message:
ValueError: No JSON object could be decoded
I am not sure what I am doing to get the data if I am getting a response status 200.
Edit:
Ran print(r.text) got this message:
<!DOCTYPE html><html lang="en"><head><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"><title>MJ Platform</title><link href="/main.b21e9284629fc8bfb7bc9b4158ad44b9.css" rel="stylesheet"></head><body><div id="defaultLoadingMessage"><div style="height:40px"></div><div class="col-md-4 col-md-offset-4"><div><h1 style="text-align:center">Loading MJ Platform</h1><div class="text-muted" style="text-align:center;width:600px;margin:auto;color:#aaa">If you continue to see this message for more than a few seconds, your browser is most likely out of date or incompatible. We support Chrome and Firefox. Other browsers may work but not provide an optimal experience. <strong>Safari and MS IE are specifically not supported.</strong></div></div></div></div><div id="app"></div><script type="text/javascript" src="/main.cccbe56cf819e9f8a6e3.js"></script></body></html>
How can browser be out of date, if I pulling information into a python anaconda window?
Was given other API information not included in documentation.

Loopback model validation is running before 'before save' observer

I'm using Loopback, Angular2 and ng-bootstrap date picker in an application and having trouble saving dates.
I'm using #angular/http to send a POST request to a Loopback backend that includes a ng-bootstrap date picker input. The date picker format is:
{
day: 15,
month: 6,
year: 2017
}
which I can see in the headers of my request, however Loopback expects dates to be saved as a JavaScript Date Object.
Before I attempt to save my date data, I want to convert it from the format above to a native JavaScript Object. However, if I run the following code the console shows Invalid Date.
MyModel.observe('before save', (ctx, next) => {
console.log('date: ', ctx.instance.date);
});
The loopback documentation states that the before save observer triggers before the request validators are called, but that doesn't look like the case in this instance.
What is the correct loopback method of accessing the POST request and modifying it before the validators sink their teeth into it and throw an error?
It looks like the remote hooks are hit before the validators. You might want to try:
MyModel.beforeRemote('create', (ctx, [instance], next)=>{
// handle code here
// don't forget to validate the data on 'updateById' too
next();
});

How to save (temporarily) form data?

There are, say, 10 fields on page1 and hyperlink to page2. Also there is hyperlink on page2 to page1. I fill 5 fields and click on the hyperlink. Then I click on the hyperlink on page2 and return to page1. Is it possible to save filled fields and how?
Additional question: what if page2 modifies fields of page1. For example, creates new choice in multichoice field.
Django has implemented solution which allow to split forms on multiple web pages. It is called form wizard. Check here for the tutorial.
EDIT 1#
Check this questions up: Django Passing data between views, How do you pass or share variables between django views?
You can save filled fields using cookies via javascript after clicking on the link and before going to another page. For example it's possible to use this jQuery plugin jQuery-cookie. As documentations says:
A simple, lightweight jQuery plugin for reading, writing and deleting cookies.
Create session cookie:
$.cookie('the_cookie', 'the_value');
Create expiring cookie, 7 days from then:
$.cookie('the_cookie', 'the_value', { expires: 7 });
Create expiring cookie, valid across entire page:
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });
Read cookie:
$.cookie('the_cookie'); // => 'the_value'
$.cookie('not_existing'); // => null
Delete cookie by passing null as value:
$.cookie('the_cookie', null);
Note: when deleting a cookie, you must pass the exact same path, domain and secure options that were used to set the cookie.

Can't subscribe to page's likes through Real-time updates API

I am trying to get updates when the like count of a page my app is on is updated. I am trying to accomplish this by using the FB Real-time Updates API
When I do a POST, with the object = "page" and the fields = "likes", I get a 400 error with the message '"likes" is an invalid field name'.
object = "page" and the fields = "name" works fine.
The documentation states you are allowed to subscribe to any public attribute.
For those playing the home game, here are the steps to reproduce the problem:
Get an OAuth token for your app:
https://graph.facebook.com/oauth/access_token?client_id=<app_id>&client_secret=<secret>&grant_type=client_credentials
Post to subscription URL:
https://graph.facebook.com/<app_id>/subscriptions
POST Variables:
'access_token' => `<access token from step 1>`,
'object' => 'page',
'fields' => 'likes',
'callback_url' => `<a callback url>`,
'verify_token' => 'testingstring123'
This isn't supported - from the section 'Real-time Updates' on https://developers.facebook.com/docs/reference/api/page/ :
The Page object supports Real-time Updates for picture, tagged and
checkins connections.
Note: Real-time updates are not yet supported for the total number of
Page checkins.
Subscribing to likes is only for pages that a user likes. The 'likes' object is what pages a user or page likes, not the count of how many people like your page, which cannot be subscribed to.