chrome.storage.sync save & load functions - google-chrome

I'm having trouble make a save & load function, here's what I'd like to do :
function save(key,val){
chrome.storage.sync.set({key:val}, function() {});
}
function load(key){
chrome.storage.sync.get([key], function(result) {return result});
}
Problem is, by doing that, my save function really create this in storage : {key: "{"key":"val"}"}
The save takes function literally takes "key", instead of taking it as a parameter.
Also, if I want load tu return my value, I need to do "result.key" instead of "result", but same problem, it takes it literally, it doesn't looks at key as a parameter.
And last problem is, if I place my return here, it doesn't work, and return nothing.
Could anyone help me fix it and understand what I did wrong please ?
ps : thanks for the asynchronous part, it helped a bit, I'll use a callback for the returned value, but it doesn't answer the other problems.

Related

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>

React get json data from http

i am newbie en react technologie.
how can i get the json data from http request ?
as you can see on
i can get the value of console.log(dataExt); from inside this function,
but i can not get the value of console.log(dataExt); from outside this function.
i miss something ?
i did use return dataExt; why i get nothing ?
i have modified my function:
async function getDataExt()
{
try {
let response = await fetch('https://xxxx');
let dataExt = await response.json();
console.log(dataExt);
return dataExt;
} catch(error) {
console.error(error);
}
}
but still i can not get the value
The fetch call is asynchronous and returns a Promise, that's why you need to call then to get the result. As it stands, line 62 will not wait for the fetch in getDataExt() to complete before running the console.log. You need to treat getDataExt as an async function and either do async/await or .then().
It is because of the asynchrony, that is, the "return" is executed when it obtains the value in the request it makes, and that takes time. Let's say it takes 1 second for the data to return, but 0.1 for the variable to print, that means it prints first and then assigns the value. Now, a possible solution would be to create a "state" to save that data or how the partner said, create the function getDataExt as an asynchronous function.

Grab data from Yahoo Finance using Meteor Package, some work some do not

I am using the following package for Meteor https://atmospherejs.com/ajbarry/yahoo-finance
I cant seem to get a specified field to work, here is a link that contains a list of all the available fields, however 'j2' and some others I tested don't work, in the sense there is no response in the result object, or no json key pair values.
Heres is my client side code.
Template.stock.rendered = function (){
if ( _.isEmpty(Session.get('ENW.V')) ) {
Meteor.call('getQuote', 'ENW.V', function(err, result) {
Session.set('ENW.V', result['ENW.V']);
console.log(result)
});
}
}
Template.stock.helpers({
stock: function() {
return Session.get('ENW.V');
}
})
Server side Method
Meteor.methods({
getQuote: function( stockname ) {
return YahooFinance.snapshot({symbols: [stockname] , fields:['n','a','b','j2'] });
}
});
Thanks for any Help in Advance. Happy to add any additional info if needed.
Did a test run after commenting out that line and it seems to work fine. Create an issue with the package owner to see if you can have it fixed for the long run.
The package you are using is deliberately excluding those fields. For what reason, I cannot say. For a full list of fields that it is avoiding, look here:
https://github.com/pilwon/node-yahoo-finance/blob/master/lib/index.js#L122

How to save the result of d3.csv.parse to a global variable?

I have this
var result;
d3.csv("xxx.csv",function(data){
csvResultParser(data);
});
function csvResultParser(data){
//parse the data then assign it to result
}
But I still have result as "undefined", any clues?
The d3.csv() function is asynchronous. Thus, you have to wait for the data to be received before reading the result variable. This is the reason why, when dealing with asynchronous data, it is prefered to do everything inside the d3.csv() function instead of using global variables.

Ext.Data.Connection request result not rendering on grid?

Ive been stuck with this issue for some time
My JSon store fields need to retrieve some more info:
{ name: "ExpirationDate", convert: convertDate },
{ name: "AffectedObject", convert: GetValue },
The date method is working fine but the result from GetValue is not being rendered on the grid even though the code is working and returning the correct value (either with or without JSON):
function GetValue(v) {
var conn = new Ext.data.Connection();
conn.request({
url: 'test/GetObjectByID',
method: 'POST',
params: { id: v },
scriptTag: true,
success: function (response) {
console.log(response.responseText);
ReturnResult(response.responseText);
},
failure: function () {
Ext.Msg.alert('Status', 'Something went wrong');
}
});
function ReturnResult(str) {
return Ext.util.JSON.decode(str.toString());
}
Any idea why the result is not not showing?
The 'convert' property is expecting an immediate return value. Your GetValue function is issuing an asynchronous request and then immediately returning nothing. At some arbitrary point in the future after the request completes the 'success' function is called, but it is no longer connected to the original call so any value it may return is meaningless.
Though you could make it work by replacing the use of Ext.data.Connection with manually constructed synchronous requests, I recommend reconsidering the mechanism by which you are getting this data. Issuing a separate request for every record in your data store is less than optimal.
The best solution is to bring that additional data in on the server side and include it in the response to the store proxy's initial request. If that cannot be done then you can try listening to the store's 'load' event and performing conversion for all loaded records with a single request. Any grids or other views you have reading from the store may have to be configured to display dummy text in place of the missing data until the conversion request completes.