Category: javascript
Category Added in a WPeMatico Campaign
Click Button to Show Alternative Section Using JavaScript
Am Using This JavaScript to Show and Hide Sections. When i click to one class it have to show another section. But the issue is when i click one class section all other classes are automatically hiding. How to fix this
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
var $ = jQuery
$(document).ready(function(){
$('[data-showme]').click( function(){
event.preventDefault();
var showme = $(this).attr('data-showme')
$('.menu-content' '.all-content' ).hide()
$('.' + showme).show()
})
})
</script>
firebase pass data to outside variable react typescript
I am trying to pass some data to a variable in react + typescript
here is what I am trying
const data = useMemo<DummyDataType[]>(
() => [
{
userId: "Foo",
flowAmount: "Bar",
},
],
[]
);
const arr: { userId: string; flowAmount: string }[] = [];
var leadsRef = db.ref('users');
leadsRef.on('value', function(snapshot) {
snapshot.forEach(item => {
arr.push({userId: 'test', flowAmount: 'test'})
})
});
const Table = useTable<DummyDataType>({
columns: columns,
data: data,
isDataLoading: false,
isDataLoadingError: false,
isRowSelectable: false,
isMultiRowSelectable: false,
});
return (
<Box p="4" color="white" bg="rgb(35, 36, 41)">
<Button colorScheme='yellow' > Save changes</Button>
{Table}
</Box>
);
so I want to push the arr to the data variable (the arr is just some dummy thing for me to test, i need the arr to reach the data var) now the problem is that the table loads before the firebase loads, and it does not render the arr. I think i need to change the data or the arr to some useState but I am not sure how that would work out
In Javascript pagination, how to not have already loaded records load again?
Say first 300 records are loaded. 150 – 200 when requested should not be loaded but retrieved from cache. Likewise if 400-500 records are loaded already, and 350-450 records are requested, only the 50 records from 350-400 should be loaded.
Passing innerHTML from View as a parameter to an ASP.NET Controller
I have a @Url.Action ASP.NET Method that looks similar to the code below:
<h1 class="sidebar-item custom-heading" id="heading-info" href="#">*Dynamically Changing Header*</h1>
<a class="sidebar-item" onclick="javascriptFunction()" href="@Url.Action("Action", "Controller", new {
name="Dynamically Changing Header",
})">Link</a>
With The Controller Method looking similar to this:
public IActionResult Action(string name) {
// operation
}
My issue I’d like to send the text inside the h1 tag(id=”heading-info”) to the controller. It’s dynamic because a there’s a java-script function that changes the innerText when called, however that shouldn’t be an issue. Ideally, what I’d want is for whatever text is in between that h1 tag to be sent to the controller whenever that link is clicked. That value will later be validated by the controller.
Let me know if this is at all possible.
Use data-attribute in javascript to alter elements width
I am still new, so please forgive me if this question is too trivial or the issue has already been discussed. I didnt find anything specific, which led me to open a new question. That said, here is how it goes:
Im passing values from my database into data-attributes in order to use them in javascript to alter the width of certain elements (i.e. graphs). The element that should be altered according to the retrieved value is a p-Tag (together with others it sits inside a foreach):
<span class="fdpg-nut-vline"><p class="fdpg-nut-graph" id="graph" data-somedat="<?php echo "'" . $value['Nu_Val'] . "%'" ?>"></p></span>
The value of the data-attribute with the name “somedat” I want to use in js, like so:
var somevar = document.getElementById('graph').getAttribute("data-somedat");
document.getElementById("graph").style.width = somevar;
What I did?
- I checked whether the format of the value is right. I therefore set a ‘static’ variable
var somevartest = '20%';and used it in the code above. It worked and the graph changed accordingly. - I checked if the value is passed into the data-attribute: (1) in the sourcode (its there!) and afterwards included an alert which shows me the value in the right format aswell (i.e. ‘x%’).
What is it that Im not getting? How can I solve my problem?
React setState don’t update values inside a promise
I’m trying to store data with my setState method inside my function but it never update it, however if I set them to a variable (I call it “x”) it works.
I have my function which returns a Promise
I hope I can get help figuring out where I went wrong or understand if it cannot be done or not.
import { NextPage } from "next";
import { useState } from "react";
import { useAirtable } from "../functions/useAirtable";
import { MyType } from "../model/MyType";
const Foo: NextPage = () => {
const [barbaz, setBarbaz] = useState<any>([]);
let x: any = [];
try {
useAirtable("My_Table").then((data: MyType) => {
setBarbaz(data);
x = data;
console.log("print1: ", data); //It PRINTS data
console.log("print2: ", barbaz); //It PRINTS empty array
console.log("print3: ", x); //It PRINTS data
}
);
} catch (error) {}
console.log("print x: ", x); //It PRINTS empty array
console.log("print barbaz: ", barbaz); //It PRINTS empty array
return <div> where is waldo </div>;
};
export default Foo;
How to create rectangles on canvas as in a graph (picture)
Can you please tell me how to implement such a graph as in the example?
I have the following test data:
[
{
day: 2,
sum: 7799857
},
{
day: 3,
sum: 6986099
},
{
day: 4,
sum: 6471975,
},
{
day: 7,
sum: 5895399,
},
{
day: 8,
sum: 5194120,
},
{
day: 9,
sum: 4851008,
},
{
day: 10,
sum: 4483119,
},
{
day: 11,
sum: 3492771,
},
{
day: 14,
sum: 2717263,
},
{
day: 15,
sum: 1763884,
},
{
day: 16,
sum: 1111772,
},
{
day: 17,
sum: 148788,
},
...
];
I don’t really understand how to separate them (as in the graph, different rectangles)
I’ll be glad for a hint.
Keep scroll position in an element on page on refresh
I set a ul of product variants with horizontal scroll. When i scroll and click on a variant, the page refresh and the scroll return to start. I need to maintain the posistion where it was first of refresh to let see the clicked variant.
ul#group_17 {
width: 150px;
display: flex;
overflow: auto;
list-style: none;
}
li {margin: 0 10px 0 0}
.input-color {
position: absolute;
opacity: 0;
cursor: pointer;
height: 60px;
width: 60px;
}
span {
height: 60px;
width: 60px;
display: block;
}
<ul id="group_17">
<li class="float-xs-left input-container">
<label>
<input class="input-color" type="radio" data-product-attribute="17" name="group[17]" value="87">
<span class="color texture" style="background:black"></span>
</label>
</li>
<li class="float-xs-left input-container">
<label>
<input class="input-color" type="radio" data-product-attribute="17" name="group[17]" value="88" checked="checked">
<span class="color texture" style="background:brown;"></span>
</label>
</li>
<li class="float-xs-left input-container">
<label>
<input class="input-color" type="radio" data-product-attribute="17" name="group[17]" value="89">
<span class="color texture" style="background:red"></span>
</label>
</li>
<li class="float-xs-left input-container">
<label>
<input class="input-color" type="radio" data-product-attribute="17" name="group[17]" value="90">
<span class="color texture" style="background:yellow"></span>
</label>
</li>
</ul>
How can i do?
Index a JS object like a Metatable in Lua
Is there a way to index an object in JavaScript like a Metatable in Lua?
Like for example:
var obj = {a:"a",b:"b",properties:{c:"c",d:"d"}}
metatable(obj,obj.properties) // Make it so that if you try to index something that's not inside the object it will go to the parameter one
console.log(obj.a) // "a"
console.log(obj.c) // "c"
how to chnage values of object coming in nested array
Im trying to chnage the object values in map loop on nested array
Object Examples
var data = [[{name: 'test', values: [{isSelected: true}] }]]
var resertData = data.map(filterArray => {
return filterArray.map(filter => {
return filter.values.map(values => {
return values.isSelected = false
})
})
})
required output should be
[[{name: 'test', values: [{isSelected: false}] }]]
and Im getting with my code
'[[[false]]]'
Please help me guys
Thanks in advance 🙂
Resolve two GraphQL schema fields using one endpoint
There’s a situation where there are two possible types to fill data property. I have made a union type for that (ComponentItem) to determine which field needs to be returned. The first schema (ComponentItem1) should just be a hardcoded list but the second one (ComponentItem2) is more dynamic where it gets a searchTerm from query and it actually calls an endpoint to fill the list and also has hasNextPage property.
Here are the schemas I made:
type Component {
id
title
data: ComponentItem
}
union ComponentItem = ComponentItem1 | ComponentItem2
type ComponentItem1 {
list: [List!]!
}
type ComponentItem2 {
hasNextPage: Boolean;
list: [List!]!
}
In the resolver I’m resolving the union type in order to generate proper __typename:
const resolver: {
CMSComponent: {
__resolveType(object) {
if(object.searchTerm){
return "ComponentItem2"
}
return "ComponentItem1"
},
},
}
What I’m currently doing is to resolve the list and hasNextPage individually but in this scenario I’m sending the request to the same endpoint twice.
const resolver = {
...resolver,
ComponentItem2: {
list: async (root, __, context) => {
const result = await fetch('search-endpoint')
return result?.items || []
}
hasNextPage: async (root, __, context) => {
const result = await fetch('search-endpoint')
return result?.hasNextPage || false
}
}
}
My question is how it is possible to share that result in another field resolver (Other than using “context”). Or if there’s any better way to handle this situation let me know.
Which DOM selector to use in selecting HTML elements [closed]
There are various DOM selector like querySelector , querySelectorAll, getElementById, getELementsByClassName and many more. But my question is when and where we should use which selector during programming. Are there any best practices that tells to specifically use the selector for this task.
How to loop through data so insert each bigquery row Node.js
In this function, it is taking cron times (expected start time) from one bigquery table (expected_sla) parsing it and the end time from that same table and inserting those two into 2 fields called expected start date and expected end time fields in the sla_table table. I want it to where it checks the dag_id and depending on the dag id insert the parsed expected start time and expected end time. Right now its just creating new rows on bigquery with these 2 dates and having all the other fields as null. I want it to where it will loop through and insert the appropriate expected start time and end time for each dag depending on the dag_id.
(async function () {
const runs = [
{
start_date: '2022-06-26T23:00:00.742495+00:00',
end_date: '2022-06-27T14:10:23.108401+00:00',
state: 'failed',
dag_run_id: 'scheduled__2022-06-25T23:00:00+00:00',
dag_id: 'EFS-Winning-Route-daily-batch'
},
{
start_date: '2022-07-07T21:20:00.566888+00:00',
end_date: '2022-07-07T23:20:55.250911+00:00',
state: 'failed',
dag_run_id: 'scheduled__2022-07-06T21:20:00+00:00',
dag_id: 'ft-parm-trumping-daily'
},
{
start_date: '2022-07-03T14:00:00.779718+00:00',
end_date: '2022-07-03T14:00:41.250433+00:00',
state: 'failed',
dag_run_id: 'scheduled__2022-06-26T14:00:00+00:00',
dag_id: 'ft-parm-trumping-weekly'
},
{
start_date: '2022-07-08T04:00:01.038023+00:00',
end_date: '2022-07-08T05:08:59.597408+00:00',
state: 'failed',
dag_run_id: 'scheduled__2022-07-07T04:00:00+00:00',
dag_id: 'IP_MASTER'
},
{
start_date: '2022-07-08T13:45:00.757997+00:00',
end_date: '2022-07-08T14:02:48.050405+00:00',
state: 'success',
dag_run_id: 'scheduled__2022-07-07T13:45:00+00:00',
dag_id: 'IPP_CYCLE_PARMS'
},
{
start_date: '2022-07-08T02:00:00.821824+00:00',
end_date: '2022-07-08T02:02:06.027268+00:00',
state: 'success',
dag_run_id: 'scheduled__2022-07-07T02:00:00+00:00',
dag_id: 'ipp-daily-backups'
},
{
start_date: '2022-07-07T23:00:01.313332+00:00',
end_date: '2022-07-07T23:02:37.032427+00:00',
state: 'failed',
dag_run_id: 'scheduled__2022-07-06T23:00:00+00:00',
dag_id: 'oclt-leadtime-daily'
},
{
start_date: '2022-07-08T13:00:00.471935+00:00',
end_date: '2022-07-08T13:00:49.819534+00:00',
state: 'success',
dag_run_id: 'scheduled__2022-07-07T13:00:00+00:00',
dag_id: 'ope-metrics'
},
{
start_date: '2022-07-07T21:30:00.682954+00:00',
end_date: '2022-07-07T21:33:29.885878+00:00',
state: 'failed',
dag_run_id: 'scheduled__2022-07-06T21:30:00+00:00',
dag_id: 'parm-lite-daily'
},
{
start_date: '2022-07-08T08:00:01.756909+00:00',
end_date: '2022-07-08T08:35:55.043131+00:00',
state: 'failed',
dag_run_id: 'scheduled__2022-07-07T08:00:00+00:00',
dag_id: 'parm-lite-data-migration'
},
{
start_date: '2022-07-03T09:00:00.825694+00:00',
end_date: '2022-07-03T09:10:31.680879+00:00',
state: 'failed',
dag_run_id: 'scheduled__2022-06-26T09:00:00+00:00',
dag_id: 'parm-lite-sunday-push-instance'
}
];
async function determineStartEnd(result){
dagID = result ? result.dag_id : 0
console.log(dagID)
job = await bqConnection().query(`SELECT * FROM `np-inventory-planning-thd.IPP_SLA.expected_sla` where dag_id = "${dagID}"`)
cronTime = job[0][0].cron_time
endTime = job[0][0].expected_end_time
var interval = parser.parseExpression(cronTime);
const d = new Date(interval.next().toString()).toISOString()
//var timeStamp = d.getTime();
//const parts = interval.next().toString().split(' ');
expectedStartDate = d
console.log(d);
console.log(endTime)
}
const date = {expected_start_date:expectedStartDate,expected_end_date:endTime}
for (let run of runs) {
await determineStartEnd(run);
await bqConnection()
.dataset('IPP_SLA')
.table('sla_table')
.insert(date);
}
}
)
();
How to conveniently use a useState value in a stored function?
I have a component that stores an array of items in a useState which are later displayed. This allows me to update the list and rerender it. I’m trying to create functions I can store and send to other components to allow them to sort my list and have the result displayed. Unfortunately, when I create and store a function, it only uses the initial value of the useState.
For example, look at my code below:
export default function MyWindow ({someAccessor}) {
const [objectList, setObjectList] = useState([])
const sortObjects = () => {
let newList = [...objectList]
newList.sort(someSortFunction)
setObjectList(newList)
}
const createAndSortObjects = () => {
let newList = [1, 2, 3, etc.]
newList.sort(someSortFunction)
setObjectList(newList)
}
useEffect(() => {
populateObjectListFunction() //Line 1
someAccessor.passFunction(sortObjects) //Line 2
someAccessor.passFunction(createAndSortObjects ) //Line 3
}, [])
return (
<div>
{objectList.mapTo(someComponentMap)}
</div>
)
}
In Line 3, if the createAndSortObjects funtion is called by the accessor, it is able to create a new array, sort it as needed, and then update my objectList variable. If I try to do the same with Line 2, however, it only uses the inital value of objectList, which is [], and replaces the array populated in Line 3.
How can I conveniently fix this issue, and have Line 2 update the existing item? I think I could probably use a useRef and access the .current value in sortObjects, but this would mean I need two separate variables to keep track of one object. I also can’t switch from my useState because then the components won’t get rerendered when the list changes. What should I do?

