Why am I getting 'Error: Error serializing ___ returned from getStaticProps'? - json

I am receiving the following error when I call inside getStaticProps and I cannot figure out why:
Error: Error serializing `.lingo` returned from `getStaticProps` in "/".
Reason: `undefined` cannot be serialized as JSON.
I've placed the full app code on CodeSandbox. It won't be able to access the API but it does show where things are defined.
When I run the following query on GraphQL playground I get the expected response:
query {
allTerms {
id
term
slug
lead
}
}
You can see that this query is contained in lingo.service.js in the modules/lingo/services directory on the sandbox but the homepage has the Error serializing error. Is my function export async function getAll() not correct or am I calling it wrong in getStaticProps?

await getAll() is most likely returning undefined which is not serializable JSON. Defaulting to null would be one way to solve the issue.
export async function getStaticProps(context) {
return {
props: { lingo: (await getAll()) ?? null },
};
}

Right, this is supposed to be more of a comment but apparently I don't have enough reputation points to comment. So, I'll answer it like this.
Just check if your props (under getStaticProps()) are named correctly i.e. how they're named in the .json file you're trying to read. I ran into this issue because of a typo I had and just fixed it.

Related

API Response returns Mappable Object in iOS but Json on Android

I'm a newbie on mobile development and React-Native, this might come across as a very mundane thing to some of you, but I'm making an Api call and then mapping the results to create the same component but with different data.
This works fine on Iphone but on Android it does not.
The response from the req is an Object for both devices but on Android, it seems to be a json object that I simply cannot map with or use on a Flatlist.
I've tried JSON.parse to get the json object to a js object but it simply doesn't, like it. It throws out an unexpected token error.
I've attached a log for the Android object first and the same object for iPhone (Already mappable and a JS object).
Can someone tell me why this happens? I'd very much appreciate it!
enter image description here
____________________ After Changing to Fetch _______________________
Hey, I changed from Axios to fetch and now I get an unhandled promise warning saying 'Unhandled promise rejection: SyntaxError: JSON Parse error: Unrecognized token '' '.
Don't think I'm doing anything wrong here...
Well ... your response-object gets truncated due to memory issues on your real-device ... most likely your response object is kinda large ...
And that's just the way axios fetch response-data ... through chunks, you just get a slice of the response...
I came across this issue before ... and the solution was to switch to fetch
Edit
try {
const rawResponse = await fetch(...);
const text = await rawResponse.text();
console.log(text);
const parsedRes = JSON.parse(text);
console.log('parsedRes', parsedRes);
} catch(error) {
console.log('fetch error', error);
}

Parse a json object shows undefined

I was using OMDBapi to get the details of different movies. I successfully fetched the result and it returns a json object like this;
{"Title":"WWA: The Inception","Year":"2001","Rated":"N/A","Released":"26 Oct 2001","Runtime":"N/A","Genre":"Action, Sport","Director":"N/A","Writer":"Jeremy Borash","Actors":"Bret Hart, Jeff Jarrett, Brian James, David Heath","Plot":"N/A","Language":"English","Country":"Australia","Awards":"N/A","Poster":"https://m.media-amazon.com/images/M/MV5BNTEyNGJjMTMtZjZhZC00ODFkLWIyYzktN2JjMTcwMmY5MDJlXkEyXkFqcGdeQXVyNDkwMzY5NjQ#._V1_SX300.jpg","Ratings":[{"Source":"Internet Movie Database","Value":"6.0/10"}],"Metascore":"N/A","imdbRating":"6.0","imdbVotes":"22","imdbID":"tt0311992","Type":"movie","DVD":"N/A","BoxOffice":"N/A","Production":"N/A","Website":"N/A","Response":"True"}
Note that we get this type of object from the api if we want to get a particular movie details and that is what i was doing. Now to show the different details to a user, i started parsing this JSON object which works fine but when i try to get the value of the Value key present inside the Ratings key, it returns undefined.
I am working with react-native. After getting the data, i stored it inside the state, named it as details. Then to get it;
this.state.details.Title //if i wanted to get the Title and it works fine.
Then for Value inside Ratings;
this.state.details.Ratings[0].Value
But it returns undefined.
Also note that this works fine in pure Javascript as i parsed the dict in the browser console in the same way and it returned the correct value.
Here is more code;
componentDidMount() {
this.fetchData();
}
fetchData = async () => {
const response = await fetch(`http://www.omdbapi.com/?i=${this.props.navigation.getParam('i')}&apikey=******`) // where this.props.navigation.getParam('i') is the omdbid of the movie
const result = await response.json()
this.setState({details: result})
}
Here is error log;
undefined is not an object (evaluating 'this.state.details.Ratings[0]')
You're most likely trying to access state object before fetch has done it's job .... it's an async op ... so you should make sure your data is ready before rendering...
if (this.state.details) {
// start rendering...
}
More Explanation
your setState function should be executed right after fetch has finished its job, and since it's an async operation, it's going to take some time ...During that time, render function is executed with no state.details --> causing your issue ...
That's why you should check for state before rendering ... besides, the optional chaining trick Silversky Technology mentioned in his answer
If the value property you are accessing from the object might be not available for all the movies in the data you are getting from API response so it might cause you to error when accessing key from undefined objects.
To overcome the issue there is a way, you can try a fix as below:
this.state.details.Ratings[0]?.Value
The ? symbol lets the javascript not give an error when the value key not available in the object. it will make the accessing of property optional.
When storing objects in states it often causes problems as you are doing in line
this.setState({details: result})
Save result after strigifying it like
JSON.stringify(result)
this.setState({details: result})
Then when fetching form state, parse it back to object by
var result = JSON.parse(this.state.details)
Then you should be able to access it
You can access Ratings[0].Value by
this.state.details.Ratings && this.state.details.Ratings[0].Value
like,
<Text> {this.state.details.Ratings && this.state.details.Ratings[0].Value} </Text>

AWS-SDK issue w/ deleteMessageBatch, telling me MissingParameter but I'm not

I'm getting the following message
UnhandledPromiseRejectionWarning: MissingParameter: The request must contain the parameter DeleteMessageBatchRequestEntry.1.Id.
I think I'm following the documentation to a T at AWS-SDK/SQS
I'm using this code
var params = {
Entries: _.map(_.uniqWith(data.Messages,d=>d.MessageId),d=>({
Id: d.MessageId,
ReceiptHandle: d.ReceiptHandle
})),
QueueUrl: xx.QueueUrl
};
await sqs.deleteMessageBatch(params).promise();
This is what params looks like at the time of sending; looks just like the docs if you ask me...
{
Entries: [
{
Id: "83ba1e18-someid",
ReceiptHandle: "AQEB79CDI1Q+blablabla"
}
]
QueueUrl: "https://sqs.us-west-2.amazonaws.com/somequeeuurl"
}
My system:
aws-sdk: "^2.354.0",
MacOS - current
node 8.12.0
UnhandledPromiseRejectionWarning: MissingParameter: The request must contain the parameter DeleteMessageBatchRequestEntry.1.Id.
I just spent a long time looking at this error and debugging my code. What I finally figured out is that it seems to be trying to say that there needs to be at least one DeleteMessageBatchRequestEntry element in the request – there can't be 0. When I refactored our code and added a check to make sure that we wouldn't make a request if there were no entries in the list, this problem went away.
Is it possible that you are actually sending the following in certain situations?
{
Entries: []
QueueUrl: "https://sqs.us-west-2.amazonaws.com/somequeeuurl"
}

How can I make Feathers (Express-based API Framework) Return Error Responses

I've read the Feathers book, so I know that to create an error response I simply instantiate the appropriate feathers-errors class:
import {BadRequest} from 'feathers-errors';
const errorResponse = new BadRequest(`foo`, `bar`);
However, I'm having difficulty returning that error response to the user. Even when I create an endpoint that does nothing but return an error response ...
class SomeService {
create(data) {
return new BadRequest(`foo`, `bar`);
}
}
it doesn't work: instead of getting an error response, I get no response, and inside the Chrome debugger I can see that the response is pending (until it eventually times out and becomes an ERR_EMPTY_RESPONSE).
I tried reading about Express error handling, and in the examples I saw people used next to wrap the the response. However, next comes from the error handler, and I'm not sure where in my Feathers code I can get that next function.
If anyone could help explain (using next or not) how I can return a complete, not pending, error response, I would greatly appreciate it.
Your services have to return a promise. If your code is not asynchronous you can turn it into a promise with Promise.resolve and Promise.reject:
class SomeService {
create(data) {
return Promise.reject(new BadRequest(`foo`, `bar`));
}
}
Also make sure you registered the Express error handler to get nicely formatted errors:
const errorHandler = require('feathers-errors/handler');
// Last in the chain
app.use(errorHandler);
There is also more information in the error handling chapter.

jsonp error with .json extension

I am using jsonp to get an external json file from the cloud. I may be being stupid but if I use this file it throws an error but works if I use a file like http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts
The json also works if I pull it in locally
function AppGuides($scope, $http) {
var url = "http://keystone-project.s3.amazonaws.com/assets/documents/AirFrance.json?callback=JSON_CALLBACK";
$http.jsonp(url)
.success(function(data){
$scope.guidedata = data;
console.log('success');
})
.error(function () {
console.log('error');
});
$scope.ddSelectSelected = {
Label: "Select an Option",
class: "hidden"
};
}
UPDATE WITH FIDDLE
http://jsfiddle.net/ktcle/a4Rc2/953/
After closer inspection and trying the code out myself, I can tell you the error is not in this angular application, but with the server where we try to download the JSON.
A simple GET request to http://keystone-project.s3.amazonaws.com/assets/documents/AirFrance.json?callback=JSON_CALLBACK reveals that the Content-Type of the returned data is application/x-unknown-content-type, when it should be application/json.
The exact error it raises is
Resource interpreted as Script but transferred with MIME type application/x-unknown-content-type
This is a server side issue, caused by whoever implemented it.
If you have access to the server code, you should change the Content-Type of the returned data.
If you do not have access, the best you can do is ask whoever does have access to fix this issue.