React Native Requires Chilkat v11.4.0+
React Native
Call a JavaScript Function Returning an Object
See more JavaScript Examples
Demonstrates how to call a JavaScript function that returns an object.Chilkat React Native Downloads
import { Js, JsonObject, StringBuilder } from '@chilkat/react-native'
async function chilkatExample() {
// This is the JavaScript function we'll call:
// function getSettings() {
// return {
// theme: "dark",
// notifications: true,
// version: 1.0
// };
// }
const sbScript = new StringBuilder();
sbScript.append('function getSettings() {');
sbScript.append(' return {');
sbScript.append(' theme: "dark",');
sbScript.append(' notifications: true,');
sbScript.append(' version: 1.0');
sbScript.append(' };');
sbScript.append('}');
const js = new Js();
const result = new JsonObject();
result.emitCompact = false;
// Call Eval to add the function to the context's global object
try {
await js.evalAsync(sbScript, result);
} catch {
// Examine the result for an exception.
console.log(result.emit());
// Also examine the LastErrorText.
console.log(js.lastErrorText);
return;
}
// ------------------------------------------------------------------------------
// Call the function getSettings()
const funcCall = new JsonObject();
// Create JSON specifying the function name and arguments
// The function has no arguments, so we only specify the name.
// {
// "name": "getSettings",
// }
funcCall.updateString('name', 'getSettings');
try {
await js.callFunctionAsync(funcCall, result);
} catch {
// Examine the result for an exception.
console.log(result.emit());
// Also examine the LastErrorText.
console.log(js.lastErrorText);
return;
}
console.log(result.emit());
// Output:
// {
// "type": "object",
// "value": {
// "theme": "dark",
// "notifications": true,
// "version": 1
// }
// }
// Examine the object's members
console.log(`theme: ${result.stringOf('value.theme')}`);
console.log(`notifications: ${result.boolOf('value.notifications')}`);
console.log(`version: ${result.intOf('value.version')}`);
// Output:
// theme: dark
// notifications: True
// version: 1
}