I have a function which should return the result array of a JSONStore query if it is successful. For some reason it doesn't return the result.
This is my function
function getJSON(){
var collectionName = 'messages';
var query = {title: 'asdf'};
var options = {
exact: false,
limit: 10
};
result = [];
WL.JSONStore.get(collectionName)
.find(query, options)
.then(function (ArrayResult) {
result = ArrayResult;
console.log(result);
console.log(typeof result);
return result;
})
.fail(function (errrorObject){
console.log("could not get JSONStore: \n" + errrorObject);
});
}
and this is where it is called:
$("#button").click( function() {
console.log("type of returned result in buttonClick: " + typeof getJSON());
})
also the console outputs appear in a weird order:
"weird orderd output" CDMS_Demo.js:96
"type of returned result in buttonClick: undefined" CDMS_Demo.html:57
"result in getJSON: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]" CDMS_Demo.js:89
"type of result in getJSON: object" CDMS_Demo.js:90
Someone got an idea how to fix it?
You seem to be expecting asynchronous code to behave synchronously. Try adding a callback, some pseudocode:
function getJSON (callback) {
var collectionName = 'messages';
var query = {title: 'asdf'};
var options = {
exact: false,
limit: 10
};
WL.JSONStore.get(collectionName)
.find(query, options)
.then(function (arrayResult) {
console.log(JSON.stringify(arrayResult));
callback(arrayResult);
})
.fail(function (errorObject){
console.log(errorObject.toString());
});
}
$("#button").click(function () {
getJSON(function (arrayResult) {
console.log(JSON.stringify(arrayResult));
});
});
Related
I'm trying to use the Jodit editor and wish to use the image uploading capabilities to specify a folder and path of where to upload it to using a PHP script.
I'm trying to put in some console.log statements to check my values, but when I select an image, I receive this error in the console which I don't know how to fix.
The code I've used in the page is:
<script>
var editor = new Jodit('#editor_Jodit',{
enableDragAndDropFileToEditor: true,
uploader: {
url: 'connector/upload.php',
format: 'json',
pathVariableName: 'path',
filesVariableName: 'images',
prepareData: function (data) {
return data;
},
isSuccess: function (resp) {
return !resp.error;
},
getMsg: function (resp) {
return resp.msg.join !== undefined ? resp.msg.join(' ') : resp.msg;
},
process: function (resp) {
return {
files: resp[this.options.uploader.filesVariableName] || [],
path: resp.path,
baseurl: resp.baseurl,
error: resp.error,
msg: resp.msg
};
},
error: function (e) {
this.events.fire('errorPopap', [e.getMessage(), 'error', 4000]);
},
defaultHandlerSuccess: function (data, resp) {
var i, field = this.options.uploader.filesVariableName;
if (data[field] && data[field].length) {
for (i = 0; i < data[field].length; i += 1) {
this.selection.insertImage(data.baseurl + data[field][i]);
}
}
},
defaultHandlerError: function (resp) {
this.events.fire('errorPopap', [this.options.uploader.getMsg(resp)]);
}
}
});
editor.value = '<p>start</p>';
</script>
Try to remove the following line:
filesVariableName: 'images'
Replace with a function
filesVariableName: function (r) {
return 'images'
},
I'm using AsyncStorage to store and retrieve an array of objects. The structure of the array is like this:
const tracks = [
{
title: title1,
exercises: [
{
object1Info...
},
{
object2Info...
}
]
},
{
title: title2,
exercises: [
{
object1Info...
}
]
},
{
title: title3,
exercises: [
{
object1Info...
}
]
}
]
As you can see, the objects in the array do themselves contain arrays, which again contain objects.
I'm storing the array like this:
const storeData = async (array) => {
try {
const stringifiedArray = JSON.stringify(array)
await AsyncStorage.setItem('#tracks_array', stringifiedArray)
} catch (e) {
console.log("Error saving data")
}
}
This seems to work fine. I then retrieve the data like this:
const retrieveData = async () => {
try {
const jsonValue = await AsyncStorage.getItem('#tracks_array');
console.log('Parsed value: ' + JSON.parse(jsonValue)); //This prints 'Parsed value: [object Object],[object Object],[object Object],[object Object]'
return jsonValue !== null ? JSON.parse(jsonValue) : null;
} catch (e) {
console.log("Error retrieving data")
}
}
This seems to work fine as well.
I have the array stored also as state. So what I want to do is add an object to the array in state, store that new array in the AsyncStorage, and then retrieve the array and set this new array back to state. Storing the object seems to have no problems.
When I retrieve the new array, and console.log(JSON.parse(jsonValue)) inside retrieveData, it prints [object Object],[object Object],[object Object],[object Object]. However after I call const newData = retrieveData(), console.log(newData) prints just [object Object]. This is my first time using AsyncStorage so I must be misunderstanding something. Why does it only return one object, instead of the whole array?
EDIT: Sharing the whole component code:
import {
StyleSheet,
ScrollView,
View,
Text
} from 'react-native';
import Modal from 'react-native-modal';
import AsyncStorage from '#react-native-community/async-storage'
import Track from './Track.js';
import New from './New.js';
class Main extends Component {
constructor(props) {
super(props);
this.state = {
tracksData: tracks,
newTrack: false,
newExercise: false
}
storeData(this.state.tracksData);
}
renderTracks(data) {
console.log('Main data = ' + data)
return data.map((item, i) => {
console.log('Item = ' + item)
return (
<Track key={i} data={item} />
)
});
}
render() {
return (
<ScrollView horizontal={true} style={styles.Main}>
{this.renderTracks(this.state.tracksData)}
<Track data={{title: 'NewTrack', exercises: 'NewTrack'}} newTrackBox={this.toggleTrackBox} />
<Modal isVisible={this.state.newTrack} coverScreen={true}>
<New type={'track'} visible={this.toggleTrackBox} add={(name) => this.addTrack(name)}/>
</Modal>
</ScrollView>
);
}
toggleTrackBox = () => {
this.setState({
newTrack: !this.state.newTrack
})
}
addTrack = (name) => {
this.setState({
newTrack: false
});
var newTracks = this.state.tracksData;
newTracks.push({title: name, exercises: []})
console.log('newTracks = ' + newTracks)
storeData(newTracks);
this.updateData();
}
updateData() {
var newData = retrieveData();
console.log('newData = ' + newData)
setTimeout(() => {
console.log('Retrieved data = ' + newData);
if (newData) {
this.setState({
tracksData: newData
});
console.log("Data updated");
return true;
} else {
console.log("Data couldn't be retrieved");
return false;
}
}, 5000)
}
}
const storeData = async (value) => {
try {
const stringifiedArray = JSON.stringify(value)
console.log('Value to store: ' + value)
console.log('Stringified value to store: ' + stringifiedArray)
await AsyncStorage.setItem('#tracks_array', stringifiedArray)
//alert("Success saving data!")
} catch (e) {
console.log("Error saving data")
alert("Error saving data");
}
}
const retrieveData = async () => {
try {
const jsonValue = await AsyncStorage.getItem('#tracks_array');
console.log('Stringified value retrieved: ' + jsonValue)
console.log('Parsed value: ' + JSON.parse(jsonValue))
return jsonValue !== null ? JSON.parse(jsonValue) : null;
} catch (e) {
console.log("Error retrieving data")
alert("Error retrieving data");
}
}
const tracks = [ //each member of this array is sent to a Track
{
title: 'Pull-up', // used in Track
exercises: [ // each member of this array is sent to an Exercise by Track
{
name: 'Pull-up', // used in Exercise
setStart: 2, // this and below used to calculate no of tiles and their contents, which are then sent to Tile
setEnd: 3,
repStart: 5,
repEnd: 8,
isInSeconds: false,
inProgress: null,
completed: true
},
{
name: 'Weighted Pull-up',
setStart: 3,
setEnd: 3,
repStart: 5,
repEnd: 8,
isInSeconds: false,
inProgress: [3, 5],
completed: false
}
]
},
{
title: 'Dip',
exercises: [
{
name: 'Dip',
setStart: 2,
setEnd: 3,
repStart: 5,
repEnd: 8,
isInSeconds: false,
inProgress: null,
completed: true
}
]
},
{
title: 'Squat',
exercises: [
{
name: 'Pistol squat',
setStart: 2,
setEnd: 3,
repStart: 5,
repEnd: 8,
isInSeconds: false,
inProgress: [2, 8],
completed: false
}
]
}
]
const styles = StyleSheet.create({
Main: {
flex: 1,
flexDirection: 'row',
backgroundColor: '#022763'
}
})
export default Main;
Also, I should have mentioned, the actual error I'm getting is:
TypeError: undefined is not a function (near '...data.map...')
"retrieveData" is async function and hence returns a Promise.
What happened was it didn't finish retrieving the data and hence newData got 1 object out of all the array.
Try changing updateData like this:
updateData() {
var newData = retrieveData().then(data => {
console.log('newData = ' + newData)
setTimeout(() => {
console.log('Retrieved data = ' + newData);
if (newData) {
this.setState({
tracksData: newData
});
console.log("Data updated");
return true;
} else {
console.log("Data couldn't be retrieved");
return false;
}
}, 5000)
};
}
I've figured out the issue. I was retrieving data with AsyncStorage, then setting that data to the state something like this:
var newData = asyncRetrieveDataFunction();
this.setState({state1: newData})
However, because I declared the retrieveData() function as async, it was setting the state before the data had finished retrieving. The solution was to use the then keyword and change it to something like this:
asyncRetrieveDataFunction().then(data => this.setState({state1: data}));
This ensures that the data has been returned BEFORE assigning it to a state.
WL.JSONStore.get(collectionName).change(data, options) method does not seem to work for duplicate values. I get duplicate values entered whenever data is loaded through the adapter. Below is the code that I have used to avoid duplicate entries.
init(){
console.log('JSONStore init function callled');
let collections = {
activities: {
searchField: {serialKey: 'string'},
adapter: {
name: 'ServiceAdapter',
add: 'pushActivities',
remove: 'removeActivity',
replace: 'replaceActivity',
load: {
procedure: 'getActivities',
params: [],
key: 'rows'
}
}
}
}
WL.JSONStore.init(collections).then((success) => {
console.log('-->JSONStore init success')
}, (failure) => {
console.log('-->JSONStore init failed', failure)
})
}
load() {
let dataRequest = new
WLResourceRequest("/adapters/ServiceAdapter/getActivities",
WLResourceRequest.GET);
dataRequest.send().then(
(response) => {
this.data = response.responseJSON.rows;
this.activityService.put(this.data);
})
}
put(data){
console.log('--> JSONStore put function called');
let collectionName = 'activities';
let options = {
replaceCriteria: ['serialKey'],
addNew: true,
markDirty: false
};
WL.JSONStore.get(collectionName).change(data, options).then((success) => {
console.log('--> JSONStore put success')
}, (failure) => {
console.log('--> JSONStore put failed', failure)
})
}
Adapter Function:
function getActivities() {
var path = 'employees' + '/_all_docs?include_docs=true';
var input = {
method : 'get',
returnedContentType : 'json',
path : path,
};
var response = MFP.Server.invokeHttp(input);
if (!response.rows) {
response.isSuccessful = false;
return response;
} else {
var results = [];
for (var i=0; i < response.rows.length; i++) {
results.push(response.rows[i].doc);
}
return {'rows': results};
}
}
I have even tried by:
searchFields: {serialKey: 'string',serialId: 'string'}
replaceCriteria: ['serialKey','serialId']
But no luck.
NOTE: There is no error in the former one, whereas the later results in an error.
ERROR : PROVISION_TABLE_SEARCH_FIELDS_MISMATCH (I have already tried to destroy the collection and perform the change, as the link suggests.
I have followed the below link:
https://www.youtube.com/watch?v=Ep6w1zXoI-k
I am using the below versions:
mfpdev : 8.0.0-2017102406
Let me know if you need any more details.
I have defined a class and am asking m.request to cast a web service's JSON response to it, but each of the class properties come out equal to n/b(), and my view renders each property as function (){return arguments.length&&(a=arguments[0]),a}.
If I do not attempt to auto-cast the JSON response to my class in m.request, then my view renders just fine, which I think tells me that the JSON object returned by the web service is valid JSON.
I want to use my class. What is wrong?
Here is an edited sample of the JSON returned by the web service:
{
"responseHeader":{
"status":0,
"QTime":0,
"params":{
"q":"blah blah",
"indent":"true",
"wt":"json"}
},
"response":{
"numFound":97,
"start":0,
"docs":[
{
"identifier":"abc123",
"heading":"A Great Heading",
"id":"abc-123-1",
"title":"A Title",
"url":"path/to/some.html",
"content":["Blah blah blah blah blee blah."]
},
{
"identifier":"xyz789",
"heading":"Another Heading",
"id":"xyz-789-1",
"title":"Another Title",
"url":"another/path/to.html",
"content":["My bonny lies over the ocean."]
}
]
}
}
Here is my Mithril app:
var findus = {};
findus.Document = function (data) {
this.id = m.prop(data.id);
this.title = m.prop(data.title);
this.heading = m.prop(data.heading);
this.identifier = m.prop(data.identifer);
this.url = m.prop("//" + data.url + "#" + data.identifier);
};
findus.vm = (function() {
var vm = {};
vm.init = function () {
// user input
vm.queryText = m.prop("");
vm.search = function () {
if (vm.queryText()) {
vm.results = m.request({
method: "GET",
url: "/prd/query?q=" + vm.queryText(),
type: findus.Document,
unwrapSuccess: function (response) {
return response.response.docs;
},
unwrapError: function (response) {
console.log(response);
}
}).bind(vm);
}
};
};
return vm;
}());
findus.controller = function () {
findus.vm.init();
};
findus.view = function () {
return [
m("input", {onchange: m.withAttr("value", findus.vm.queryText), value: findus.vm.queryText()}),
m("button", {onclick: findus.vm.search}, "Search"),
findus.vm.results ? m("div", [
findus.vm.results().map(function (result) {
return m("div", [
m("h2", result.heading),
m("p", result.content),
m("a", {href: result.url}, result.url)
]);
})
]) : ""
];
};
m.module(document.body, {controller: findus.controller, view: findus.view});
Oh, bugger. I forgot that my class properties are getter/setters via m.prop, so I should have been calling them as functions in the view -- see below.
False alarm, problem solved, I'm embarrassed.
findus.view = function () {
return [
m("input", {onchange: m.withAttr("value", findus.vm.queryText), value: findus.vm.queryText()}),
m("button", {onclick: findus.vm.search}, "Search"),
findus.vm.results ? m("div", [
findus.vm.results().map(function (result) {
return m("div", [
m("h2", result.heading()),
m("p", m.trust(result.content())),
m("a", {href: result.url()}, result.url())
]);
})
]) : ""
];
};
In my app I want define JSON schemas for custom API.
For example from: http://docs.strongloop.com/display/public/LB/Remote+methods#Remotemethods-Example
module.exports = function(Person){
Person.greet = function(msg, cb) {
cb(null, 'Greetings... ' + msg);
}
Person.remoteMethod(
'greet',
{
accepts: <generate definitions from jsonschema>,
returns: <generate definitions from jsonschema>
}
);
};
How to do that?
This is right way?
MY SOLUTION - validation decorator + remote method params with object type
var validate = require('jsonschema').validate;
bySchema = function (schema) {
return function (func) {
return function () {
var data = arguments[0],
callback = arguments[1];
var result = validate(data, schema);
if (result.errors.length > 0) {
// some errors in request body
callback(null, {
success: false,
error: 'schema validation error',
});
return;
}
return func.apply(this, arguments);
};
};
};
defaultRemoteArguments = {
accepts: {
arg: 'data',
type: 'object',
http: function(ctx) {
return ctx.req.body;
}
},
returns: {
arg: 'data',
type: 'object',
root: true
}
};
Example:
Auth.login = bySchema(require('<path to shcemajson json for this request>'))
(function(data, cb) {
// process request
});
Auth.remoteMethod('login', defaultRemoteArguments);
In this solution contrib loopback explorer will not be useful, because request/response are objects, not fields...
The correct way to do it is to set the type in the returns attribute to the model name.
In your case you would write:
Person.remoteMethod(
'greet',
{
...
returns: {type:'Person', ...}
}
);
You need to modify your output to match the format accepted by the returns property.
...
returns: [{arg: "key1", type: "string"}, {arg: "key2", type: "object"}, ...];
...