Using Axios with react-chrono - reactjs

I am not able to get react chrono working when I tried to use the state data. I did a console log on conversationData and is it did print out and as well as conversationtracking. I did get an error that says: "Expected an assignment or function call and instead saw an expression". I am wondering where did I go wrong? here is the code of what I am trying to do:
const data = [
conversationData.map(record => record.conversationtracking.map(items => {
{
{
title: moment(items.conversationdate).format('MMMM DD, YYYY')
cardTitle: items._id
cardSubtitle: items.name
cardDetailedText: items.text
}
}
}))
];
return (
<div>
<h1>sdvsdv</h1>
<Chrono
items={data}
mode="VERTICAL"
/>
</div>
)

You needed return the data after map. Also you were missing , in your object defined inside the second map loop.
PS: The way you are trying to double map the objects will impact the performance. You may need to find a better way to save that extra loop.
// As per the map structure, I hope the data is like this
var conversationData = [{
conversationtracking: [{
_id: 1,
name: 'AVC0',
text: 'RESDS',
conversationdate: '23/12/2020'
}]
}]
const data = [
conversationData.map(record => record.conversationtracking.map(items => {
return {
title: items.conversationdate,
cardTitle: items._id,
cardSubtitle: items.name,
cardDetailedText: items.text
}
}))
];
console.log(data)

Related

What is the ideal way to use subscription with react apollo GraphQL

I am working on a react project which uses GraphQl for API integration, which I did perfectly.
Now I am working on a module where I need to use subscription.
What I am doing
I have charts to show one UI, which I have created successfully using ReCharts.
So initially I a getting data from query and displaying it on UI which works totally fine.
Than as per requirement There is some live data which I am getting through subscription i.e web socket
So what I am doing is I stored query data in a state and when I got the live data I am appending the live data to that state and UI is updating correctly.
Issue I am facing
As I have many charts on UI so I am conditionally checking for which chart I am getting data and than appending to the particular one.
But what happens is when I got a lot of data which is coming every 2-6 seconds it hangs the browser after sometime, like after 10 minutes or 15 minutes, which is bit frustrating.
I don't know What is wrong in this, may be my approach is not good or something else
My code what I did
// below query is for getting list of factoories
//const { loading: loadingFactoryy, data: factoryList } = useQuery( FACTORYLIST);
// from above query I ll get data like below state
// as I am not connected to backend so I am taking data statically
const [factoryList, setFactoryList] = useState([
{
factoryId: 16,
factoryName: "factory one",
__typename: "user_factoryNames"
},
{
factoryId: 17,
factoryName: "factory two",
__typename: "user_factoryNames"
},
{
factoryId: 18,
factoryName: "factory Three",
__typename: "user_factoryNames"
},
{
factoryId: 19,
factoryName: "factory four",
__typename: "user_factoryNames"
}
]);
My Machine code
// below query to get the machines for each factories, if i click on
//factoryone it will give me all machines of factory one
// const [
// getMachines,
// { loading: loadingMachines, data: machineData },
// ] = useLazyQuery(FACTORYMACHINEBYID);
//I am using lazyquery so when I click I ll get the data
// useEffect(() => { this will run when page loades first time
// if (factoryList !== undefined) {
// if (factoryList.getUserFactorydNames.length > 0) {
// getInitialDataFun({
// variables: {
// factoryId:
// factoryList?.getUserFactorydNames[parseInt(activeDashboard)]
// ?.factoryId,
// },
// });
// }
// }
// }, [active_tab, factoryId, getInitialDataFun]);
//all functions for factories click
let active_tab = localStorage.getItem("active_tab") || 0;
const [active_menu, setActive_menu] = useState(Number(active_tab));
const [machineList, setmachineList] = useState([
{
chartId: 12,
chartBame: "machine1",
data: [
{
dValue: 5,
dName: "Data1"
},
{
dValue: 10,
dName: "Data2"
}
]
},
{
chartId: 13,
chartBame: "machine2",
data: [
{
dValue: 5,
dName: "Data1"
},
{
dValue: 10,
dName: "Data2"
}
]
}
]);
My subscription code
// my subscription code
// const {
// data: LiveDataMachine,
// error: errorLiveDataMachine,
// } = useSubscription(LIVEDATAMACHINEFUN, {
// variables: { topic: { topic: 'livemessage/' } },
// });
const factoryClick = (li, ind) => {
setActive_menu(ind);
localStorage.setItem("active_tab", ind);
};
//My live data looks like below
// {
// "chartId": 16,
// "chartBame": "machine1",
// "data": [
// {
// "dValue": 7,
// "dName": "Data1"
// },
// {
// "dValue": 18,
// "dName": "Data2"
// }
// ]
// }
// So what I am doing is whenever I am getting the live data
//I am looping it with main machine data and checking for chartId
//once it matches I am appending the data like below
// useEffect(() => {
// if(machineList){
// machineData.map((li,ind)=>{
// if(LiveDataMachine.chartId===li.chartId){
// setmachineList(machineList=>[...machineList,LiveDataMachine])
// }
// })
// }
// }, [LiveDataMachine]);
// but what is hapenning is it is updating the UI so fast that my browser is getting hanged
return (
<div className="App">
<FactoryComp
factoryData={factoryList}
active_menu={active_menu}
factoryClick={factoryClick}
/>
<hr />
<MachinesComp machineData={machineList} />
</div>
above is how I am writing my code and managing GraphQl subscription, I don't know what I am doing wrong which is making my browser hangs alot
here I am looking for a correct approach by which I can use subscription with my query.
Here is my working code I have written everything as a comment for better uderstanding
Looks like you are calling setmachineList in the if inside a render. It will endlessly cause component updates, thereby cycling it. Perhaps it is better to move this logic to useEffect?
useEffect(() => {
if(machineList){
machineData.forEach((li,ind)=>{
if(LiveDataMachine.chartId===li.chartId){
setmachineList(machineList=>[...machineList,LiveDataMachine])
}
})
}
}, [LiveDataMachine]);

ANGULAR Components array key in result get value by id

this.crudService.get('user.php?mode=test')
.subscribe((data:any) => {
{ for (var key in data) { this[key] = data[key]; } };
}
);
This use to work on angular 7 now on angular 13 i get this error (look image)
In template i was using the values for example in json string was and array and i had users, in template was {{users}} , {{posts}} etc.. now the this[key] give error , please help me out its very important can't find solution
i'll show an example code, and then applied to your code:
Example
// creating global variables to receive the values
users: any = null;
posts: any = null;
// simulating the data you will receive
data: any[] = [
{users: ['user1', 'user2', 'user3']},
{posts: ['post1', 'post2', 'post3']}
];
getCrudService() {
// access each object of the array
this.data.forEach(obj => {
// getting keys name and doing something with it
Object.keys(obj).forEach(key => {
// accessing global variable and setting array value by key name
this[String(key)] = obj[String(key)]
})
})
}
Apllied to your code
this.crudService.get('user.php?mode=test').subscribe((data:any) => {
data.forEach(obj => {
Object.keys(obj).forEach(key => {
this[String(key)] = obj[String(key)]
});
});
});
I hope it helped you, if you need help, just reply me.

Block Context in editor.BlockEdit filter

I’m trying to extend a core gutenberg block so that it has a couple of additional options only when it’s contained in a certain custom made block. I thought block context would make this a simple task — set the container block to providesContext and use the blocks.registerBlockType filter to add usesContext to the core block. In the editor.BlockEdit filter, I thought I’d be able to get context from the block’s props. However, context is not one of the props. To make sure I wasn’t doing anything wrong around context, I used the editor.BlockEdit filter on one of my custom blocks that I knew was receiving block context correctly. It doesn’t have context as one of its props either.
Does anyone know of a way to get block context into the editor.BlockEdit filter?
For reference, here is a snippet of the code so far:
title: 'Card',
icon: 'images-alt2',
category: 'utdesign_system',
description: '',
attributes: {
blockName: {
type: 'string',
default: 'card',
}
},
providesContext: {
'card/blockName': 'blockName',
},
edit,
save,
} );
function addImageContext( settings ) {
if( settings.name == 'core/image' ){
settings.usesContext = Object.assign( ['card/blockName'] );
}
return settings;
}
addFilter(
'blocks.registerBlockType',
'gutenstrap/image-context',
addImageContext
);
const addImageControls = createHigherOrderComponent( ( BlockEdit ) => {
return ( props ) => {
const {
name,
attributes,
setAttributes,
context,
isSelected,
} = props;
//do stuff with context
};
}, "addImageControls" );
addFilter(
'editor.BlockEdit',
'gutenstrap/image-context',
addImageControls
);```
It is now documented https://developer.wordpress.org/block-editor/reference-guides/block-api/block-context/
registerBlockType( 'my-plugin/record-title', {
title: 'Record Title',
category: 'widgets',
usesContext: [ 'my-plugin/recordId' ],
edit( { context } ) {
return 'The record ID: ' + context[ 'my-plugin/recordId' ];
},
save() {
return null;
},
} );

React : Pushing result of map() to an array

Hello I am trying to map through an array of objects and push them to a new array.
My ISSUE : only the last item of the object is being pushed to the new array
I believe this has to do with React life cycle methods but I don't know where I should I loop and push the values to the array to get the full list
//My object in an array named states
var states = [{"_id":"Virginia","name":"Virginia","abbreviation":"VN","__v":0},{"_id":"North Carolina","name":"North Carolina","abbreviation":"NC","__v":0},{"_id":"California","name":"California","abbreviation":"CA","__v":0}];
export function StateSelect()
{
**EDIT 1**
const options = [];
function getStates()
{
//This is how I am looping through it and adding to an array
{ states.length > 0 &&
states.map(item =>
(
console.log(`ITEM: ${JSON.stringify(item)}`),
options.push([{ value: `${item.name}`, label: `${item.name}`}])
))
}
}
return( {getStates()}: );
}
Thank you
It looks like your getStates() might not even be returning anything... but assuming it is, I believe you should be able to accomplish this using a forEach() fn in order to push values into your options array... Try adding the following into your map:
states.map((item) => {
console.log(`ITEM: ${JSON.stringify(item)}`);
let processed = 0;
item.forEach((i) => {
options.push([{ value: `${i.name}`, label: `${i.name}`}]);
processed++;
if(processed === item.length) {
// callback fn, or return
}
}
.map usually used to return another result, you could just use .forEach
In fact, you don't really need to declare options at all, just use .map on state to return the result would be fine.
return states.length > 0 && states.map(({ name }) => {
return { value: name, label: name };
});

tfjs codelab 'making predictions from 2D data' use of values keyword in tf-vis.render.scatterplot

Why can't I replace values with another variable name like values1?
values is a js keyword, so I think there is something really fancy going on here.
In this codelab:
https://codelabs.developers.google.com/codelabs/tfjs-training-regression/index.html#2
In this code snippet:
async function run() {
// Load and plot the original input data that we are going to train on.
const data = await getData();
const values = data.map(d => ({
x: d.horsepower,
y: d.mpg,
}));
tfvis.render.scatterplot(
{name: 'Horsepower v MPG'},
{values},
{
xLabel: 'Horsepower',
yLabel: 'MPG',
height: 300
}
);
// More code will be added below
}
The tfjs documentation doesn't require the use of the values keyword:
https://js.tensorflow.org/api_vis/latest/#render.scatterplot
If I set up the HTML as instructed in the tutorial and use the same js code, I get the expected plot in my browser (firefox).
If I use the following js code, it breaks. Browser remains completely blank, console error message states: TypeError: r is undefined
In the code below, values in both places is changed to values1. That's the only change.
async function getData() {
const dataRequest = await fetch('https://storage.googleapis.com/tfjs-tutorials/carsData.json');
const data = await dataRequest.json();
const cleaned = data.map(car => ({
mpg: car.Miles_per_Gallon,
hp: car.Horsepower,
}))
.filter(car => (car.mpg != null && car.hp != null));
return cleaned
}
async function run() {
// Load and plot the original input data that we are going to train on.
const data = await getData();
const values1 = data.map(d => ({
x: d.hp,
y: d.mpg,
}));
tfvis.render.scatterplot(
{name: 'Horsepower v MPG'},
{values1},
{
xLabel: 'Horsepower',
yLabel: 'MPG',
height: 300
}
);
// More code will be added below
}
document.addEventListener('DOMContentLoaded', run);
I'd expect the above code to result in a plot as with the original code, but I get no plot and a TypeError instead.
values is not a js keyword. It is a property of the object data that is a parameter of scatterplot. If you want to change the const values to values1, you have to do the following:
tfvis.render.scatterplot(
{name: 'Horsepower v MPG'},
{values: values1},
{
xLabel: 'Horsepower',
yLabel: 'MPG',
height: 300
}
)

Resources