AsyncStorage.getItem("item") returns the string "[object Object]" - react-native

I'm using AsyncStorage in order to save a "session" in my app, and I do so in this piece of code:
if (signInResult) {
if (signInResult.userId && signInResult.accessToken) {
await AsyncStorage.setItem("auth", signInResult);
}
this.props.navigation.navigate("home");
}
But when I tried to get the data back with AsyncStorage.getItem("auth"), it just retrieves the string [object Object]
I tweaked the code a but to write stuff in the console so I could keep tabs on the data, so here's what I encountered so far:
So there I logged the same data before and after putting it "through" the AsyncStorage. First, we see that the object is still very much a javascript object, and the second is just the name o the type, apparently. I'm not sure what's going on here, but I'm pretty sure this should work. I actually use that same approach in another app and I don't have this issue there.
Thanks in advance.

You need to JSON.stringify & JSON.parse while saving and getting data from AsyncStorage.
if (signInResult) {
if (signInResult.userId && signInResult.accessToken) {
await AsyncStorage.setItem("auth", JSON.stringify(signInResult));
}
AsyncStorage.getItem("auth").((item) => {
JSON.parse(item);
});
this.props.navigation.navigate("home");
}

Related

how to reload value after clicking in vue

I'm trying to reload values when switching tab without reloading the page. I'm getting the value from a method.
mounted() {
this.getOriginalSpace();
},
methods: {
getOriginalSpace() {
retrieveQuotaSummary(this.value.organisation, this.value.dataCenter)
.then((result) => {
this.quotaSummary = result;
});
}
}
after that, I read the needed value out of quotaSummary like this (computed):
previouslyYarnCPU() {
return this.quotaSummary.currentAcceptedYarnRequest
? this.quotaSummary.currentAcceptedYarnRequest.cpu
: 0;
},
Then, when I switch tab, and call an other function in computed mode, I still have the same value which was loaded above. But when I refresh the page, then I get the correct (new value).
Can someone please help me, how I can get the latest values without refreshing the whole page?
It is difficult as I would need to see the rest of your code but in order to get values when they change you need to use a computed function. You can read more here

Is it okay to update or delete data inside of router.post, instead of .delete/.patch?

I created some example code underneath to show what I mean.
Is it okay to update some data after saving inside of a post route? I often update and save data in a single route, and I never know if it is okay to do this and if there are any consequences of the code that I am unaware of.
router.post('/sync-steam', auth, async(req, res) => {
const { steamID, steamName } = req.body
try {
await req.user.save( steamID )
await req.user.updateOne( steamName )
res.send("OK")
} catch(err) {
res.status(400).send(err)
}
})
Yes, it is OK to do that. There should not be any issues regarding that as long as your logic that communicates with your database is correct.
However, you should try to follow the convention of REST API, and use the correct method:
GET for listing/reading content
POST for creating content
PUT for replacing content
PATCH for updating part of the content
DELETE for deleting content

Component method response object data binding

I am starting to lose my mind in debugging an application that I inherited from a fellow developer who is absent.
I have narrowed down the problem to the following place in code (php files are checked, Vue instances are initialised, there are no syntax errors).
This is my the component that gets initialised:
var RadniStol = Vue.component('radnistol', {
template: '#template-RadniStol',
data() {
return {
tableData: [],
requestData: {
sort: "ID",
order: "DESC"
}
}
},
methods: {
reloadTable: function (event) {
data = this.requestData;
this.$http.post('php/get/radni_stol.php', data).then(response => {
console.log(response.data.bodyText);
this.tableData = response.data.records;
});
},
.
.
.
The PHP file that gets called with the POST method is working correctly, querying the database and echoing the response in a JSON format.
The thing that is making me pull out my hair is the following: the console.log(response.data) outputs the following into the console:
{"records":[{"DODAN_NA_RADNI_STOL":"1","..."}]}
It is an JSON object that I expected to have but when trying to assign it to the data of the component with:
this.tableData = response.data;
or any other way… response.data.records returns ‘undefined’ in the console. I have tryed with JSON.parse() but no success.
When logging types to console:
response variable is a response object with a status 200 and body and bodyText containing the data from the database.
response.data is a string type containing the string JSON with the data from the database.
When trying to use JSON.parse(response.data) or JSON.parse() on anything in the callback of the POST method I get the following error in the console:
RadniStol.js?version=0.1.1:17 Uncaught (in promise) SyntaxError: Unexpected token in JSON at position 0
at JSON.parse (<anonymous>)
at VueComponent.$http.post.then.response (RadniStol.js?version=0.1.1:17)
at <anonymous>
I am really starting to lose my mind over this issue, please help!
Thank you
If response.data is string, with JSON inside, then to access the records field, you should decode it like this:
JSON.parse(response.data).records
Not sure this has something to do with PHP or Vue.js, it is just plain javascript issue.
If it not decodes, than problem is definitely in response.data. For example
{"records":[{"DODAN_NA_RADNI_STOL":"1","..."}]}
is not a valid JSON, because key "..." needs to have some value.
But it seems to me that response.data is already parsed.
What I suggest you to do, is to write handler of the response as separate function, make response object that mimics actual response object by hand, and then test it separately from request. So you could show us request object and function that works with it.
I had the same error and fixed it.
Result will be response.body not response.data.
Here is my code:
getS: function(page) {
this.$http.get('vue-manager?page=' + page).then((response) => {
var data = JSON.parse(response.body);
this.student = data.data.data;
this.pagination = data.pagination;
});
},

EmberJS Route to 'single' getting JSONP

I'm having trouble with EmberJS to create a single view to posts based on the ID, but not the ID of the array, I actually have a ID that comes with the json I got from Tumblr API.
So the ID is something like '54930292'.
Next I try to use this ID to do another jsonp to get the post for this id, it works if you open the api and put the id, and actually if you open the single url with the ID on it, works too, the problem is:
When, on the front page for example, I click on a link to go to the single, it returns me nothing and raise a error.
But if you refresh the page you get the content.
Don't know how to fix and appreciate some help :(
I put online the code: http://tkrp.net/tumblr_test/
The error you were getting was because the SingleRoute was being generated as an ArrayController but the json response was not an Array.
App.SingleController = Ember.ObjectController.extend({
});
Further note that the model hook is not fired when using linkTo and other helpers. This because Ember assumes that if you linked to a model, the model is assumed to be as specified, and it directly calls setupController with that model. In your case, you need to still load the individual post. I added the setupController to the route to do this.
App.SingleRoute = Ember.Route.extend({
model: function(params) {
return App.TKRPTumblr.find(params.id);
},
setupController: function(controller, id) {
App.TKRPTumblr.find(id)
.then(function(data) {
controller.set('content', data.response);
});
}
});
I changed the single post template a bit to reflect how the json response. One final change I made was to directly return the $.ajax. Ember understands jQuery promises directly, so you don't need to do any parsing.
Here is the updated jsbin.
I modified: http://jsbin.com/okezum/6/edit
Did this to "fix" the refresh single page error:
setupController: function(controller, id) {
if(typeof id === 'object'){
controller.set('content', id.response);
}else{
App.TKRPTumblr.find(id)
.then(function(data) {
controller.set('content', data.response);
});
}
}
modified the setupController, since I was getting a object when refreshing the page and a number when clicking the linkTo
Dont know if it's the best way to do that :s

KoLite asyncCommand accessing element data

So I'm displaying a observable array in my view, and I want to be able to remove an element from that list using asyncCommand. However, I'm not sure how I should be getting that element. Is there a way of accessing or passing the selected element into the asyncCommand method?
Thanks for the input
addGroupCmd = ko.asyncCommand({
execute: function (data, complete) {
//access your observable here with the data object
//EX. var demo = data.id();
},
canExecute: function (isExecuting) {
return !isExecuting && isEditing();
}
}),
Ok, so I figured it out with it little bit of google's help. All you have to do is pass in the data parameter and ko.lite will figure out what object your talking about. pretty nice, not really sure how it works, but it does.