react native- json parsing (cant parse json object in my code) - json

Here is my code. In this I got x but when I try to parsing x for getting object of x 'isloggedin' it gives error. what should I do wrong tell me if you understand my problem.
componentDidMount() {
this.onLoad();
}
onLoad = async () => {
try {
var walletdata = await AsyncStorage.getItem('wallet');
this.setState({x: JSON.parse(walletdata)})
this.setState({y: JSON.stringify(this.state.x)})
console.log("output: "+ this.state.y);
console.log("output y:"+JSON.parse(this.state.y.isloggedIn));
}catch(error){
console.log("error: "+error);
}
}
error: SyntaxError: JSON Parse error: Unexpected identifier "undefined"

Probably is because 'wallet' key has undefined value in the caché storage. You should check first the value (right after getting the item from the storage) and if it's undefined then you have to set it first.

Probably you need to wait for the first setState function to finish, So that you can get access to it in second call.
In short, It will take some time for setting your value in State and you are trying to access it before updating the state. So try to access the values in the callback of setState function.
Instead of this,
this.setState({x: JSON.parse(walletdata)})
this.setState({y: JSON.stringify(this.state.x)})
console.log("output: "+ this.state.y);
console.log("output y:"+JSON.parse(this.state.y.isloggedIn));
You can use this:
this.setState({x: JSON.parse(walletdata),y: JSON.stringify(walletdata.x)},()=>{
console.log("output: "+ this.state.y);
console.log("output y:"+JSON.parse(this.state.y.isloggedIn));
});

I have solved my problem. Thank you for your answers. below is how could I solved my question.
try {
var walletdata = await AsyncStorage.getItem('wallet');
this.setState({wallet: JSON.stringify(JSON.parse(walletdata))})
this.setState({isLoggedin:JSON.parse
(this.state.wallet).isLoggedin});
console.log(this.state.isLoggedin);
}catch(error){
console.log("error: "+error);
}

Related

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

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.

Q.nfcall: TypeCast fails on an unspecified error

I'm learning node, and I'm having a hard time writing the back-end code for my database interactions. A promise based implementation looked a lot cleaner than doing it all using callbacks, so I did some digging and found Q.
I'm having trouble understanding what I'm doing wrong here, or even where. The error function inside .then seems to be catching the TypeCast error, but I don't know what I'd be doing that would be causing that error?
Running the following script
mysql = require('mysql');
var q = require('q')
var dbx = mysql.createConnection({
//this is verified correct...
});
function getuser3(UserDisplayName) {
return q.nfcall(dbx.query, "SELECT * FROM Users WHERE Name = ? ", [UserDisplayName])
// This should wrap the query function with a promise, apply the arguments "SELECT..." ,
// [UserDisplayName], and set up the last-argument-node-style callback so it fulfills the promise
// with either a value or an error. If I understand correctly.
}
val = getuser3("Player2")
.then(
function (value) {
console.log(value)
return value //this should be sent to val in the outside scope, right?
},
function (error) {
console.log(error)
}
)
.done()
console.log(val)
Returns the following error:
c:\Users\cb\Documents\guts\learning node\backend\node_modules\q\q.js:155
throw e;
^
TypeError: Cannot read property 'typeCast' of undefined
at query (c:\Users\cb\Documents\guts\learning node\backend\node_modules\mysql\lib\Connection.js:185:34)
at Promise.apply (c:\Users\cb\Documents\guts\learning node\backend\node_modules\q\q.js:1185:26)
at Promise.promise.promiseDispatch (c:\Users\cb\Documents\guts\learning node\backend\node_modules\q\q.js:808:41)
at c:\Users\cb\Documents\guts\learning node\backend\node_modules\q\q.js:1411:14
at runSingle (c:\Users\cb\Documents\guts\learning node\backend\node_modules\q\q.js:137:13)
at flush (c:\Users\cb\Documents\guts\learning node\backend\node_modules\q\q.js:125:13)
at processTicksAndRejections (internal/process/task_queues.js:79:11)
Process exited with code 1
I've tried several variations of the syntax, reading the docs as best I could, but I really don't know where to go next.

Json data only loads correct once you refresh the page?

I have two issues but I believe the second issue will be fixed once the first is fixed (question title).
I am receiving JSON from woocommerce. I can call for this data by using fetch of course on client side and it looks as such in the code:
async componentDidMount() {
const response = await fetch('/products');
const json = await response.json();
this.setState({
data: json,
})
// other code ....
}
When I go on the browser I get this error regarding my json data:
Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0
With the following error in the console.log:
index.js:6 GET http://localhost:3000/products 500 (Internal Server Error)
index.js:6 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Once the webpage is refreshed...this all disappears, everything becomes A-OKAY, why? and how do I go about rectifying this?
My JSON data when consoled and the page refreshed returns an object - no '<' is there. Also I don't know why I get the 500 error shown above? I am learning node.js - so I think this is a server side issue as I had no issues before I split my code to client and server.
help?
What is happening is the data call you do takes time to load the data.
Till then the this.state.data is null. The error
Unexpected token < in JSON at position 0
is because you are trying to process the this.state.data but finds null. You need to make sure you handle what needs to be displayed when data is null.
Also, I think you don't need the await before response.json()
The 500 server error is a server side issue.
To stop this whole refreshing the page issue; I had to fix my server file (node.js of course)
My get request had originally looked like this:
let response;
app.get('/products', (req, res, err) => {
WooCommerce.get('products', function(err, data, res) {
response = res;
});
res.status(200).json(JSON.parse(response));
});
The issue here was that I was calling /products with fetch which url didn't point to anything but another API call, which only got called once I forced it pass the first url call I guess using a page refresh. Forgive my understanding here.
The correct code was calling Woocommerce api first then passing its response to the /product url so I can fetch it in the front end, like so;
let response;
WooCommerce.get('products', function(err, data, res) {
response = res;
app.get('/products', (req, res, err) => {
if (res.status(200)) {
res.status(200).json(JSON.parse(response));
} else {
console.log('theres an error', err);
}
})
});
And Tarrrrdaaa no refresh issue/SyntaxError error!!!
As one of the answers says, this error happens when you try to parse a nullish value. You can fix this issue by making sure the data is defined before trying to parse it:
if(data){
JSON.parse(data);
}

How to get data from Nodejs to angular 6?

I'm using http.get to get data from nodejs to angular. I want load some content on page loading. So, I'm just calling it in initialize method.
_initialize(): void {
this.http.get('http://127.0.0.1:3000/query/getId').subscribe(
data => {
console.log("success");
},
err => {
console.log("Error occured."+JSON.stringify(err));
}
);
}
In my server js,
app.get('/query/getId',function(req,res){
console.log("hi there");
})
I want to pass the data, but as of now the console message itself not displaying in node. And in browser I could see the message error occured. message":"Http failure during parsing for the url" . Can anybody tell me how to proceed with this?
You can specify that the data to be returned is not a JSON using the responseType. See the Requesting non JSON data
In your example, you should be able to use:
this.http.post('http://127.0.0.1:3000/query/getId',{}, {responseType: 'text'})
Add on node function:
res.json("hi there");
Try the following which uses JSON data:
app.get('/query/getId',function(req,res){
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ a: 1 }));
});

read JSON using angular2

I have problem with json\object I'M trying to pull the data out from it and I failed.
I have this API that I pull my data from:
http://api.fixer.io/latest?base=CAD
I have placed it on variable results,
If i want to get to object paramater date,base,rate like below:
calc(details) {
let results = [this.networkServices.getCurrency(details)]; // object is here "getCurrency deal with the GET request.
alert(results.base);
}
I get the error code:
[02:58:36] transpile update started ...
[02:58:38] typescript: D:/ionic/firstApp/src/pages/currency/currency.ts, line: 19
Property 'base' does not exist on type 'Promise<any>[]'.
L18: let results = [this.networkServices.getCurrency(details)];
L19: alert(results.base);
[02:58:38] transpile update failed
Its feel weird that I can't pull the data out, what could it be?
get currency function
getCurrency(obj){
console.log("function fired!")
let url = `http://api.fixer.io/latest?base=${obj.selectedCurrency}`;
return this.http.get(url).toPromise().then(res => res.json());
}
Try updating your getCurrency() to just return the promise by removing the then():
getCurrency(obj){
console.log("function fired!")
let url = `http://api.fixer.io/latest?base=${obj.selectedCurrency}`;
return this.http.get(url).toPromise();
}
Then the solution from #pe8ter should work:
this.networkServices.getCurrency(details).then(result => alert(result))
The service request is asynchronous so the result of the request is a Promise that resolves to an object, not the object itself. Try something like this:
this.networkServices.getCurrency(details).then(result => alert(result))