What could be the possible reason? This is my Image and getRows code
getRows: (params: IServerSideGetRowsParams) => {
const { startRow, endRow, sortModel, filterModel } = params.request;
if (startRow === 0 && initialRender) {
getDashboardTableData({
variables: {
result: 'ProjectSummary',
startRow: startRow,
endRow: endRow,
tab: state.tab,
headerFilter: state.card,
filtergroup: JSON.stringify(state?.defaultFilter),
sortModel: JSON.stringify(sortModel?.length ? sortModel[0] : {}),
},
}).then((response) => {
if (response?.data) {
const { datarows, total } = JSON.parse(response?.data?.lpapqpprojectsumm.body);
if (response?.data?.lpapqpprojectsumm?.statusCode === '200') {
params?.success({
rowData: datarows,
rowCount: total,
});
}
} else {
params?.fail();
}
}).catch((error) => {
params?.fail();
});
}
Related
I've been trying to resolve this issue where using the Gutenberg meta box updates, doesn't fetch the new updated meta value.
Meta registration:
add_action('init', function() {
register_meta('post', 'open_unit', array(
'type' => 'string',
'single' => true,
'show_in_rest' => true,
'auth_callback' => function() {
return current_user_can('edit_posts');
}
));
register_meta('post', 'open_active', array(
'type' => 'boolean',
'single' => true,
'show_in_rest' => true,
'auth_callback' => function() {
return current_user_can('edit_posts');
}
));
register_meta('post', 'open_abstract', array(
'type' => 'string',
'single' => true,
'show_in_rest' => true,
'sanitize_callback' => function($text) {
return sanitize_text_field($text);
},
'auth_callback' => function() {
return current_user_can('edit_posts');
}
));
});
Enqueue assets:
add_action('enqueue_block_editor_assets', function() {
$screen = get_current_screen();
if ($screen->post_type === 'page') return;
wp_enqueue_script(
'open-panel',
plugin_dir_url( __FILE__ ) . 'js/admin.js',
array('wp-i18n', 'wp-blocks', 'wp-edit-post', 'wp-element', 'wp-editor', 'wp-components', 'wp-data', 'wp-plugins', 'wp-edit-post', 'wp-api-fetch'),
filemtime(dirname( __FILE__ ) . '/js/admin.js')
);
});
Javascript:
const el = element.createElement;
const { Fragment } = element;
const { registerPlugin } = plugins;
const { PluginDocumentSettingPanel } = editPost;
const { TextareaControl, ToggleControl, Text } = components;
const { withSelect, withDispatch, subscribe, registerStore } = data;
const ActiveCheckboxControl = compose.compose(
withDispatch(function(dispatch, props) {
return {
setMetaValue: function(metaValue) {
dispatch('core/editor').editPost(
//{ meta: { [props.metaKey]: (openValidate && metaValue) } }
{ meta: { [props.metaKey]: metaValue } }
);
}
}
}),
withSelect(function(select, props) {
return {
metaValue: select('core/editor').getEditedPostAttribute('meta')[props.metaKey],
}
}))(function(props) {
return el(ToggleControl, {
label: props.title,
checked: props.metaValue,
onChange: function(content) {
props.setMetaValue(content);
},
});
}
);
const AbstractTextControl = compose.compose(
withDispatch(function(dispatch, props) {
return {
setMetaValue: function(metaValue) {
dispatch('core/editor').editPost(
{ meta: { [props.metaKey]: metaValue } }
);
}
}
}),
withSelect(function(select, props) {
return {
metaValue: select('core/editor').getEditedPostAttribute('meta')[props.metaKey],
}
}))(function(props) {
return el(TextareaControl, {
label: props.title,
value: props.metaValue,
onChange: function(content) {
props.setMetaValue(content);
}
});
}
);
registerPlugin('open', {
render: function() {
return el(Fragment, {},
el(PluginDocumentSettingPanel,
{
name: 'open',
title: 'Open'
},
// Active
el(ActiveCheckboxControl,
{
metaKey: 'open_active',
title : 'Show'
}
),
// Abstract
el(AbstractTextControl,
{
metaKey: 'open_abstract',
title : 'Abstract'
}
)
)
);
}
});
...
let isSavingChecked = true;
let editor = data.select('core/editor');
const getOpenUnit = () => editor.getEditedPostAttribute('meta') ? editor.getEditedPostAttribute('meta').open_unit : null;
const getOpenActive = () => editor.getEditedPostAttribute('meta') ? editor.getEditedPostAttribute('meta').open_active : false;
const getOpenAbstract = () => editor.getEditedPostAttribute('meta') ? editor.getEditedPostAttribute('meta').open_abstract : null;
let openUnit = getOpenUnit();
let openActive = getOpenActive();
let openAbstract = getOpenAbstract();
console.log(openUnit);
const unsubscribe = subscribe( _.debounce( () => {
const isSavingPost = editor.isSavingPost();
const newOpenUnit = getOpenUnit();
const newOpenActive = getOpenActive();
const newOpenAbstract = getOpenActive();
if (isSavingPost) {
isSavingChecked = false;
} else {
if(!isSavingChecked) {
let post = editor.getCurrentPost();
let data = {
active: openActive ? 'active':'paused',
abstract: post.meta.open_abstract,
wp_id: post.id,
wp_title: post.title,
wp_url: post.link,
wp_image: post.featured_media
}
let openValidation = openValidate(data);
if (openValidation.valid) {
if(openActive !== newOpenActive || openAbstract !== newOpenAbstract || openUnit !== newOpenUnit) {
openRemote(data);
} else {
console.log(newOpenUnit); //This field is not returning the updated meta field from Wordpress
openRemoteUpdate(data);
}
} else {
wp.data.dispatch('core/notices').removeNotice('OPEN_NOTICE');
wp.data.dispatch('core/notices').createNotice(
'warning',
openValidation.messages.join(', '),
{ id: 'OPEN_NOTICE', isDismissible: true }
);
}
isSavingChecked = true;
openActive = newOpenActive;
openAbstract = newOpenAbstract;
openUnit = newOpenUnit;
}
}
}));
I am basically trying to fetch the updated meta field:
const getOpenUnit = () => editor.getEditedPostAttribute('meta') ? editor.getEditedPostAttribute('meta').open_unit : null;
But it's currently looking like this in the console where it's null(console.log(openUnit)) or empty(console.log(newOpenUnit)) https://share.getcloudapp.com/E0uYKWGv Lines 195 & 224
Any help or advice would be appreciated!
The easiest way I have found to get and set meta is using useEntityProp() in a function component. It is a lot easier to reason about than using withSelect and withDispatch.
import { __ } from '#wordpress/i18n';
import { useSelect } from '#wordpress/data';
import { useEntityProp } from '#wordpress/core-data';
import { TextControl } from '#wordpress/components';
export default function MetaComponent(props) {
const postType = useSelect((select) => {
return select('core/editor').getCurrentPostType();
});
const [meta, setMeta] = useEntityProp('postType', postType, 'meta');
return (
<TextControl
label={ __('Meta', 'pb') }
value={ meta.open_abstract ? meta.open_abstract : '' }
onChange={ (value) => setMeta({open_abstract: value}) }
/>
);
}
I have a set of JSON objects having the wsDestAddress key, so how do I traverse the JSON objects or do a wild search for wsDestAddress key in present JSON objects to find the key is present or not and returning null or ""?
JSON Object #1
{
"gfutd": {
"wsRequestData": {
"wsDestAddress": ""
}
}
}
JSON Object #2
{
"igftd": {
"wsRequestData": {
"wsDestAddress": ""
}
}
}
JSON Object #3
{
"y7igfutd": {
"wsResponseData": {
"wsDestAddress": ""
}
}
}
JSON Object #4
{
"y7igptdf": {
"wsRequestData": {
"returnAddress": {
"wsDestAddress": ""
}
}
}
}
I know this code works fine
if (y7igfutd.wsRequestData.wsDestAddress == "" ||
igftd.wsRequestData.wsDestAddress == "" ||
y7igfutd.wsResponseData.wsDestAddress == "" ||
y7igfutd.wsRequestData.returnAddress.wsDestAddress == "") {
return "result"
}
But I want to do a wild search for wsDestAddress as the JSON keys search.
Here is an answer using object-scan. Your requirements were not entirely clear, but I'm sure you can easily adjust the below code to meet your needs.
// const objectScan = require('object-scan');
const data1 = { gfutd: { wsRequestData: { wsDestAddress: '' } } };
const data2 = { igftd: { wsRequestData: { wsDestAddress: '' } } };
const data3 = { y7igfutd: { wsResponseData: { wsDestAddress: '' } } };
const data4 = { y7igptdf: { wsRequestData: { returnAddress: { wsDestAddress: '' } } } };
const data5 = { y7igptdf: { wsRequestData: { returnAddress: { other: '' } } } };
const search = objectScan(['**.wsDestAddress'], {
filterFn: ({ value }) => value === '',
rtn: 'bool',
abort: true
});
console.log(search(data1));
// => true
console.log(search(data2));
// => true
console.log(search(data3));
// => true
console.log(search(data4));
// => true
console.log(search(data5));
// => false
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#14.0.0"></script>
Disclaimer: I'm the author of object-scan
You can find the first item that has a "wsDestAddress" value of "" via:
const data = [
{ "y7igfutd" : { "wsResponseData" : { "wsDestAddress" : "" }}},
{ "igftd" : { "wsRequestData" : { "wsDestAddress" : "" }}},
{ "y7igfutd" : { "wsResponseData" : { "wsDestAddress" : "" }}},
{ "y7igptdf" : { "wsRequestData" : { "returnAddress" : { "wsDestAddress" : "" }}}}
];
// Adapted from: https://stackoverflow.com/a/40604638/1762224
const findValue = (object, key) => {
let value;
Object.keys(object).some(k => {
if (k === key) {
value = object[k];
return true;
}
if (object[k] && typeof object[k] === 'object') {
value = findValue(object[k], key);
return value !== undefined;
}
});
return value;
};
const oneMatches = (arr, key, value) =>
arr.some(item => findValue(item, key) === value);
const allMatches = (arr, key, value) =>
arr.every(item => findValue(item, key) === value);
console.log(oneMatches(data, 'wsDestAddress', '')); // Some = true
console.log(allMatches(data, 'wsDestAddress', '')); // Every = true
I have an array of objects called audioBaby.
When the app launches I check asyncStorage and if any key has value active, I want to update the lock keys in the array.
What I have done is not updating all objects in array but only the last object.
How can I initially update the array from asyncStorage and render the screen?
const [audioBaby, setAudioBaby] = useState([
{
lock: "deactive",
url: "item0.mp3",
},
{
lock: "deactive",
url: "item1.mp3",
},
{
lock: "deactive",
url: "item2.mp3",
},
]);
useEffect(() => {
try {
AsyncStorage.multiGet([
"babyAudio0Status", //value: active
"babyAudio1Status", //value: active
"babyAudio2Status", //value: active
]).then((response) => {
let updatedList = audioBaby;
if (response[0][1] != "null" && response[0][1] == "active") {
updatedList = audioBaby.map((item) => {
if (item.url == "item0.mp3") {
return { ...item, lock: "active" };
}
return item;
});
}
if (response[1][1] != "null" && response[1][1] == "active") {
updatedList = audioBaby.map((item) => {
if (item.url == "item1.mp3") {
return { ...item, lock: "active" };
}
return item;
});
}
if (response[2][1] != "null" && response[2][1] == "active") {
updatedList = audioBaby.map((item) => {
if (item.url == "item2.mp3") {
return { ...item, lock: "active" };
}
return item;
});
}
setAudioBaby(updatedList)
});
} catch (error) {
console.log("error::", error);
}
}, []);
Final array should be like this:
[
{
lock: "active",
url: "item0.mp3",
},
{
lock: "active",
url: "item1.mp3",
},
{
lock: "active",
url: "item2.mp3",
},
]
I moved all ifs to inside of map function and everything is fine.
let updatedList = audioBaby.map((item) => {
if (item.url === 'item0.mp3' && response[0][1] === 'active') {
return { ...item, lock: 'active' }
}
if (item.url === 'item1.mp3' && response[1][1] === 'active') {
return { ...item, lock: 'active' }
}
if (item.url === 'item2.mp3' && response[2][1] === 'active') {
return { ...item, lock: 'active' }
}
return item
})
I'm trying to make a test using jest with Vue.
the details below.
Problem:
Can't mount using shallowMount option.
Situation:
Run the test after mounting the component using shallowMount option that provides in Vue-test-utils.
Throw error "Cannot read property 'XXXX' of undefined
This is my test code.
import myComponent from '#/~';
import Vuex from 'vuex';
import Vuelidate from 'vuelidate';
import { shallowMount, createLocalVue } from '#vue/test-utils';
const localVue = createLocalVue();
localVue.use(Vuex);
localVue.use(Vuelidate);
describe('myComponent~', () => {
let store;
beforeEach(() => {
store = new Vuex.Store({
modules: {
user: {
namespaced: true,
getters: {
profile: () => {
const profile = { name: 'blahblah' };
return profile;
},
},
},
},
});
});
describe('profile.name is "blahblah"', () => {
it('return something~', () => {
const wrapper = shallowMount(myComponent, {
localVue,
store,
mocks: {
$api: {
options: {
testMethod() {
return new Promise((resolve, reject) => {
resolve('test');
});
},
},
},
$i18n: {
t() {
return {
EN: 'EN',
KO: 'KO',
JP: 'JA',
SC: 'zh-CN',
TC: 'tw-CN',
};
},
},
},
});
expect(wrapper.find('.profile').text()).toBe('blahblah');
});
I think the problem is that property isn't set as a specified value or an empty value like an array or object.
But I don't know how I set properly the properties in my logic.
For example,
when the error yields "Cannot read property 'images' of undefined",
I add to a wrapper in the relevant method like this.
exampleMethod() {
this.something = this.something.map(item => {
if (item.detailContent.images) { // <-- the added wrapper is here
~~~logic~~~~
}
})
}
But the undefined properties are so many, I also think this way is not proper.
How I do solve this problem?
added
These are details about the above example method:
exampleMethod() {
this.something = this.something.map(item => {
let passValidation = false;
let failValidation = false;
if (item.detailContent.images) {
if (this.detail.showLanguages.includes(item.code)) {
if (this.configId !== 'OPTION1') {
item.detailContent.images = item.detailContent.images.map(element => {
return {
...element,
required: true,
}
});
}
checkValidationPass = true;
} else {
if (this.configId !== 'OPTION1') {
item.detailContent.images = item.detailContent.images.map(element => {
return {
...element,
required: false,
}
});
}
checkValidationPass = false;
}
return {
...item,
required: passValidation,
warning: failValidation,
}
}
});
if (this.configId === 'OPTION2') {
this.checkOption2Validation();
} else if (this.configId === 'OPTION3') {
this.checkOption3Validation();
} else {
this.checkOption1Validation();
}
},
And this is 'this.something':
data() {
return {
something: []
}
}
The detailContent is set here.
setMethod() {
this.something = [
...this.otherthings,
];
this.something = this.something.map(item => {
let details1 = {};
if (this.configId === 'OPTION2') {
details1 = {
images: [
{ deviceType: 'PC', titleList: [null, null], imageType: 'IMAGE' },
{ deviceType: 'MOBILE', titleList: [null, null, null] }
]
};
} else if (this.configId === 'OPTION3') {
details1 = {
images: [
{ deviceType: 'PC' },
{ deviceType: 'MOBILE' }
],
links: { linkType: 'EMPTY' },
};
}
let details2 = {
mainTitle: {
content: null,
}
}
let checkValidation = false;
this.detail.detailLanguages.forEach(element => {
if (element.language === item.code) {
details1 = { ...element };
if (!!element.mainTitle) {
details2 = { ...element };
} else {
details2 = {
...details2,
...element
};
}
if (this.configId !== 'OPTION1') {
details1.images = details1.images.map(image => {
return {
...image,
required: true,
}
});
}
checkValidation = true;
}
});
return {
...item,
detailContent: this.configId !== 'OPTION1' ? details1 : details2,
required: false,
warning: false,
}
});
},
I am using map function to iterate an object. but in one scenario i have to use nested map function. I try to add an value to an empty object inside an map function, but instead of adding values it replacing it. can anyone help me with this?
// object stores final results
let valid_data={}
//object to iterate
let test_cases = {
sample:
[ { test_case_no: 1,
test_case_description: 'user-status active - response 200',
value: 'active',
response_code: 200,
valid: 'yes' },
{ test_case_no: 2,
test_case_description: 'user-status inactive - response 200',
value: 'inactive',
response_code: 200,
valid: 'no' },
{ test_case_no: 3,
test_case_description: ' inappropriate user-status - response 400',
value: 'notAdmin',
response_code: 400,
valid: 'no' } ],
sample1: [ { obj1: [Array], obj2: [Array], test_case_no: 4 } ]
}
//my code to iterate an object
Object.entries(test_cases).map((property) => {
const field_name = property[0]
const field_definition = property[1]
Object.entries(field_definition).map((property) => {
if (property[1].valid != 'yes' && property[1].valid != 'no') {
Object.entries(field_definition).map((property) => {
Object.entries(property[1]).map((propertyy) => {
Object.entries(propertyy[1]).map((property) => {
nested_data = []
nested_value = {}
if (property[1].valid == 'yes') {
nested_value[propertyy[0]] = property[1].value
nested_data.push(Object.assign({}, nested_value))
valid_data[field_name] = (Object.assign({}, nested_value))
}
})
})
})
}
else if (property[1].valid == 'yes') {
valid_data[field_name] = property[1].value;
}
})
})
console.log(valid_data);
Actual result:
“{ sample: 'active',
sample1: { obj2: 2019-07-01T09:50:46.266Z } }”
Expected result:
“{ sample: 'active',
sample1: [{ obj1: 2019-07-01T09:50:46.266Z,obj2: 2019-07-01T09:50:46.266Z }] }”
Wrong var initialisation in your code.
Try this loop :
Object.entries(test_cases).map((property) => {
const field_name = property[0]
const field_definition = property[1]
Object.entries(field_definition).map((property) => {
if (property[1].valid != 'yes' && property[1].valid != 'no') {
nested_value = {}
Object.entries(property[1]).map((propertyy) => {
Object.entries(propertyy[1]).map((property) => {
if (property[1].valid == 'yes') {
nested_value[propertyy[0]] = property[1].value;
valid_data[field_name] = (Object.assign({},
nested_value))
}
})
})
} else if (property[1].valid == 'yes') {
valid_data[field_name] = property[1].value;
}
})
});
Working jsfiddle
Object.entries(test_cases).map((property) => {
const field_name = property[0]
const field_definition = property[1]
Object.entries(field_definition).map((property) => {
if (property[1].valid != 'yes' && property[1].valid != 'no') {
nested_data = []
nested_value = {}
Object.entries(property[1]).map((propertyy) => {
Object.entries(propertyy[1]).map((property) => {
if (property[1].valid == 'yes') {
nested_value[propertyy[0]] = property[1].value;
if(!nested_data.includes(nested_value)){
nested_data.push(nested_value)
valid_data[field_name] = nested_data
}
}
})
})
} else if (property[1].valid == 'yes') {
valid_data[field_name] = property[1].value;
}
})
})