I am implementing a payment engine in my online store and I want to obtain the details of the card with which you are paying (payment details). I would like to know if this is possible?
Category: javascript
Category Added in a WPeMatico Campaign
How can I console log all rest paramaters without using a loop? (Including objects and no toString)
What is the configuration in Google Chart to lessen the number of number/dates display on the hAxis?
I’m using a line graph in Google Chart and there’s just one thing left I need to configure, the hAxis dates.
The dates have 2 days gap only, like Feb 2, Feb 4, Feb 6, Feb 8, and so on, and so it shows 15 dates on the hAxis. I want to widen the gap maybe by 7 days or lessen the number of dates displayed by just 4 dates. How to achieve that? I can’t seem to find the right config for it here: https://developers.google.com/chart/interactive/docs/gallery/linechart.
Here’s my chart: https://jsfiddle.net/r2wxayn8/
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Price');
data.addRows([
[new Date(2022, 1, 1), 0.2500], [new Date(2022, 1, 2), 0.2500], [new Date(2022, 1, 3), 0.2600], [new Date(2022, 1, 4), 0.2700], [new Date(2022, 1, 5), 0.2800], [new Date(2022, 1, 6), 0.3000],
[new Date(2022, 1, 7), 0.2900], [new Date(2022, 1, 8), 0.3300], [new Date(2022, 1, 9), 0.3100], [new Date(2022, 1, 10), 0.3200], [new Date(2022, 1, 11), 0.3200], [new Date(2022, 1, 12), 0.3200],
[new Date(2022, 1, 13), 0.3100], [new Date(2022, 1, 14), 0.3200], [new Date(2022, 1, 15), 0.3000], [new Date(2022, 1, 16), 0.3100], [new Date(2022, 1, 17), 0.3000], [new Date(2022, 1, 18), 0.3000],
[new Date(2022, 1, 19), 0.2900], [new Date(2022, 1, 20), 0.2800], [new Date(2022, 1, 21), 0.2700], [new Date(2022, 1, 22), 0.2700], [new Date(2022, 1, 23), 0.2700], [new Date(2022, 1, 24), 0.2600],
[new Date(2022, 1, 25), 0.2700], [new Date(2022, 1, 26), 0.2600], [new Date(2022, 1, 27), 0.2500], [new Date(2022, 1, 28), 0.2500], [new Date(2022, 1,29), 0.2400], [new Date(2022, 1, 30), 0.2500]
]);
var options = {
hAxis: {
gridlines: {
color: 'none'
},
format: 'MMM dd',
textStyle: {
color: '#677185',
fontSize: 12,
bold: true
}
},
vAxis: {
gridlines: {
color: '#DFE3EB'
},
minorGridlines: {
color: '#DFE3EB'
},
textStyle: {
color: '#677185',
fontSize: 12,
bold: true
}
},
tooltip: {
textStyle: {
color: '#677185',
fontSize: 12
}
},
series: {
0: {
color: '#26a172'
}
},
legend: { position: 'none' },
curveType: 'function'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
Iterating over deeply nested objects
I have data that looks like this:
{
FL: [{ID: 1, confirmed: true},{ID: 2, confirmed: false}],
TX: [{ID: 3, confirmed: true}],
NY: [{ID: 4, confirmed: false}, {ID: 5, confirmed: true}]
}
And I need to be able to loop over each item in this data find the one
who’s ID === a known ID. I’m not sure the best way to approach this.
The only thing that I can come up with is a for-In loop but Id have to map over the arrays after looping over the object so that doesn’t seem very clean.
Is there any method that is clean for handling iterating over such deeply nested data?
Working with big nested object as state in React
Hello fellow developers,
I’m junior developer and I’m working on a project with big nested object (example bellow) which ideally I want to use as react state that can be accessed from multiple places but I don’t know which approach is best for this solution as I don’t have many experiences yet. If you could give me some advice, code example or link to some tutorial or blog, it would be very helpful.
My current approach (example bellow) is to use useContext without useReducer because I just don’t want to just export dispatch because I think is kinda ugly or not programmer friendly as you always have to define different type and payloads. Maybe I could wrap dispatch it in the functions but I’m just not sure about it. I was also thinking about using Redux, but I don’t use that yet and according to what read that it can be overkill for this.
Thank you in advance.
{
id: string,
name: string,
sections: [{
id: string,
pos_x: number,
pos_y: number,
rows: number,
columns: number,
curvature: number,
skew: number,
rotation: number,
section_type: string,
name: string,
seats: [{
id: string,
row: number,
column: number,
is_disabled: boolean,
category: string,
name: string,
created_at: string,
updated_at: string,
is_reserved: boolean,
reserved_at: string,
status: string,
ticket: number
}],
total_seats: number,
created_at: string,
updated_at: string,
available_seats: number,
purchased_seats: number,
reserved_seats: number
}],
creator: number,
account: number,
is_editable: boolean,
total_seats: number,
created_at: string,
updated_at: string,
event: number,
available_seats: number,
purchased_seats: number,
reserved_seats: number
}
import React, {createContext, FC, useState} from 'react';
import {Seat, SeatMap, Section} from "../../types/seatmapData";
type UpdateSelectedSectionProps = (section: Section, seatIndex: number) => Section
export interface ISeatMap {
id: string,
name: string,
sections: Section[],
creator: number,
account: number,
isEditable: boolean,
totalSeats: number,
createdAt: string,
updatedAt: string,
event: number,
availableSeats: number,
purchasedSeats: number,
reservedSeats: number
}
export interface ISeatMapContext extends ISeatMap {
setName: (name: string) => void;
setSections: (section: Section[]) => void;
setId: (id: string) => void;
setCreator: (creator: number) => void;
setAccount: (account: number) => void;
setIsEditable: (isEditable: boolean) => void;
setTotalSeats: (totalSeats: number) => void;
setCreatedAt: (createdAt: string) => void;
setUpdatedAt: (updatedAt: string) => void;
setEvent: (event: number) => void;
setAvailableSeats: (availableSeats: number) => void;
setPurchasedSeats: (purchasedSeats: number) => void;
setReservedSeats: (reservedSears: number) => void;
addSectionToSelected: (section: Section) => void;
removeSectionsFromSelected: (section: Section) => void;
clearSelectedSections: () => void;
addSeatToSelected: (section: Section, seat: Seat) => void;
removeSeatFromSelected: (section: Section, seat: Seat) => void;
clearSelectedSeats: () => void;
addSection: (section: Section) => void;
removeSection: (section: Section) => void;
removeSelectedSections: () => void;
updateSection: (section: Section) => void;
updateSelectedSeats: (updateFunction: UpdateSelectedSectionProps) => boolean;
reserveSelectedSeats: (reserved: boolean, reservedAt: Date) => void;
purchaseSelectedSeat: () => void;
disableSelectedSeats: (disabled: boolean) => void;
getSeatMap: () => void;
}
export const SeatMapContext = createContext<ISeatMapContext>(null!);
export interface SeatMapProviderProps extends FC {
children: any;
initialValue: SeatMap;
}
const SeatMapProvider = ({ children, initialValue }: SeatMapProviderProps) => {
const [name, setName] = useState<string>(initialValue.name)
const [sections, setSections] = useState<Section[]>(initialValue.sections)
const [id, setId] = useState<string>(initialValue.id)
const [creator, setCreator] = useState<number>(initialValue.creator)
const [account, setAccount] = useState<number>(initialValue.account)
const [isEditable, setIsEditable] = useState<boolean>(initialValue.is_editable)
const [totalSeats, setTotalSeats] = useState<number>(initialValue.total_seats)
const [createdAt, setCreatedAt] = useState<string>(initialValue.created_at)
const [updatedAt, setUpdatedAt] = useState<string>(initialValue.updated_at)
const [event, setEvent] = useState<number>(initialValue.event)
const [availableSeats, setAvailableSeats] = useState<number>(initialValue.available_seats)
const [purchasedSeats, setPurchasedSeats] = useState<number>(initialValue.purchased_seats)
const [reservedSeats, setReservedSeats] = useState<number>(initialValue.reserved_seats)
const [selectedSections, setSelectedSections] = useState<Section[]>([]);
const [selectedSeats, setSelectedSeats] = useState<{section: Section, seat: Seat}[]>([]);
const addSectionToSelected = (section: Section) => {
setSelectedSections(prev => [...prev, section])
}
const removeSectionsFromSelected = (section: Section) => {
setSelectedSections(prev => prev.filter(s => s.id === section.id))
}
const clearSelectedSections = () => {
setSelectedSections([])
}
const addSeatToSelected = (section: Section, seat: Seat) => {
setSelectedSeats(prev => [...prev, {section: section, seat: seat}])
}
const removeSeatFromSelected = (section: Section, seat: Seat) => {
setSelectedSeats(prev => prev.filter(s => s.section.id === section.id && s.seat.id == seat.id))
}
const clearSelectedSeats = () => {
setSelectedSeats([])
}
const addSection = (section: Section) => {
setSections(prevState => [...prevState, section])
}
const removeSection = (section: Section) => {
setSections(prevState => prevState.filter(s => s.id == section.id))
}
const removeSelectedSections = () => {
if(selectedSections.length == 0) return
setSections(prevState => {
const notSelected: Section[] = []
prevState.forEach(s => {
let isSelected = false
selectedSections.forEach(selected => {
if(selected.id == s.id) isSelected = true
})
if(!isSelected) notSelected.push(s)
})
return notSelected
})
}
const updateSection = (section: Section) => {
setSections((prevState) => {
const index = prevState.findIndex(s => s.id === section.id)
sections[index] = section
return sections
})
}
const updateSelectedSeats = (updateFunction: UpdateSelectedSectionProps): boolean => {
if(selectedSections.length == 0 || selectedSeats.length == 0) return false
const updateTime = new Date().toISOString()
setSections(sections => {
selectedSeats.forEach(({section, seat}) => {
const sectionIndex = sections.findIndex(s => s.id === section.id)
const seatIndex = sections[sectionIndex].seats.findIndex(s => s.id === seat.id)
const newSection = updateFunction(sections[sectionIndex], seatIndex);
sections[sectionIndex] = newSection
sections[sectionIndex].updated_at = updateTime
})
return sections
})
setUpdatedAt(updateTime)
return true
}
const reserveSelectedSeats = (reserved: boolean, reservedAt: Date) => {
const updated = updateSelectedSeats((section, seatIndex) => {
section.seats[seatIndex].is_reserved = reserved
section.seats[seatIndex].reserved_at = reservedAt.toISOString()
return section
})
if(updated) setReservedSeats(prev => reserved ? ++prev : --prev)
}
const purchaseSelectedSeat = () => {
}
const disableSelectedSeats = (disabled: boolean) => {
const updated = updateSelectedSeats((section, seatIndex) => {
section.seats[seatIndex].is_disabled = disabled
if(disabled) section.total_seats--
else section.total_seats++
return section
})
if(updated) setTotalSeats(prev => disabled ? --prev : ++prev)
}
const getSeatMap = (): SeatMap => {
return {
name: name,
sections: sections,
id: id,
creator: creator,
account: account,
is_editable: isEditable,
total_seats: totalSeats,
created_at: createdAt,
updated_at: updatedAt,
event: event,
available_seats: availableSeats,
purchased_seats: purchasedSeats,
reserved_seats: reservedSeats,
}
}
return (
<SeatMapContext.Provider value={{
name, setName,
sections, setSections,
id, setId,
creator, setCreator,
account, setAccount,
isEditable, setIsEditable,
totalSeats, setTotalSeats,
createdAt, setCreatedAt,
updatedAt, setUpdatedAt,
event, setEvent,
availableSeats, setAvailableSeats,
purchasedSeats, setPurchasedSeats,
reservedSeats, setReservedSeats,
addSectionToSelected,
addSeatToSelected,
clearSelectedSeats,
clearSelectedSections,
purchaseSelectedSeat,
removeSeatFromSelected,
removeSectionsFromSelected,
getSeatMap,
addSection,
removeSection,
updateSection,
removeSelectedSections,
updateSelectedSeats,
reserveSelectedSeats,
disableSelectedSeats
}}>
{children}
</SeatMapContext.Provider>
)
};
export default SeatMapProvider;
vs code power-shell doesn’t recognize npm command
My vs code power-shell doesn’t recognize my command … but cmd works just fine … What is the problem ? … i am currently working on a react js project and i am install npm and yarn then i face these problem… so how can i solve it as soon as possible or i freshly install node and others thing
Kill process.exec function
I have a function to execute a process:
static async runTest() { await process.exec(`start ${currentDir}/forward.py`); }
runTest();
The python script will continue to run until it’s killed, which I don’t know how to do at the moment. So in short, I want to kill this process manually at some point. How I would I do this? Thank you!
Is it valid to mutate an array prop in a child component?
I’ve noticed when pushing to an array that has been passed to a child component as prop, I don’t get the usual ‘Avoid mutating a prop directly’ error. After thinking about it, this makes sense because the array is a reference and if something causes the parent to re-render, the child will render correctly because of this.
Is the proper approach still to emit to the parent and have the parent operate on the array, or is it perfectly valid to operate on the array in the child component since it is a reference?
Vue – Loop through an array with nested objects
I’m fetching a list that I’m trying to loop through that has an object inside. I’m using vue and the array looks like this:
companies: [
name: "company1"
id: 1
type: "finance"
additionalData: "{"funder":"blabla","idType":5,"number":"2"}"
]
My problem is accessing the different ones inside the additionalData.
This is how far I’ve come:
<div
v-for="(company, idx) in companies"
:key="idx"
>
<p class="font-weight-bold text-h6"> {{ company.name }} </p>
<p class="font-weight-bold"> {{ company.additionalData.funder }} </p>
</div>
This doesn’t work and I’ve tried a loop inside the loop aswell. When I only print out {{ company.additionalData }} I get the whole object. Can it have something to do with that the object is inside a string? Could I do a computed or something to figure this out or? 🙂
Define characters in a string
I want to be able to reserve 2 or more characters in a string. For example:
let string = " "
string.unknownMethod("a")
What function do I need in place of unknown method
to get this output " a"
. But if string.unknownMethod("ab")
the output should be "ab"
Remove sorting from Datatable in checkboxes
var table = $('#mytable').DataTable({
'columnDefs': [{
'targets': 0,
'searchable': false,
'orderable': false,
'className': 'checkbox check-success'
}],
'order': [[1, 'asc']]
});
<div class="checkbox check-success">
<label class=" mt-checkbox mt-checkbox-outline"
for="checkbox_<?php echo $valuep['0'] ;?>">
<input id="checkbox_<?php echo $valuep['0'] ;?>" type="checkbox" name="leads_ids" value="<?php echo $valuep['0'] ;?>" class="select_click">
<span></span>
</label>
<input type="hidden" id="enable_all"
name="enable_all" value="1">
<input type="hidden" id="lead_contact_id_<?php echo $valuep['0'] ;?>"
name="contact_id" value="<?php echo $valuep['0'] ;?>">
</div>
<span id="custom_controls"></span>
</td>
Whenever I click on select-all on top of table it gets back to first page.I need to select some rows in table and export it to csv but when selecting on different pages when i click on select all it gets back to page 1.
Javascript – Sort columns in table by date while rows content changes
I have a table/Div like the one below, and the data is generated dynamically in real time so the rows keep coming and changing.
The table is floating on my browser, I dont have control over the source website so I cannot use jquery to modify the table. I can ONLY use javascript, (by using the browser extension) to alter the DOM.
I need the javascript code that can:
- sort the table by the date and time – newest on top
- highlight rows that have the word: “blocked”
- hide rows that have the word: “unknown” (but make the rows appear when the content is changed to something else)
- keep sorting when timeCell or descriptionCell is updated in any row (or maybe run the sorting every 30 seconds)
I am not familiar with the modern JS code but I think that the date time can be changed to unix timestamp so it make the sorting easier.
I tried to use Chrome browser extension called: Javascript Injector and some javascript code that uses const, i.e: const tabledoc = document;
But when I click the update button of the extension, it will show me some error that says tabledoc is already defined.
Can you please help me?
<div class="container-QqYJdG">
<div class="wrapper-QqYJdG">
<div class="bodyRow-3OfxA">
<div class="cell-3OfxA symbolCell-3OfxA">
<div class="Name-3OfxA">MacKenzi</div>
</div>
<div class="cell-3OfxA descriptionCell-3OfxA">visited</div>
<div class="cell-3OfxA timeCell-3OfxA"><span>1/11/2022</span><span>1:59:08 PM</span></div>
</div>
<div class="bodyRow-3OfxA">
<div class="cell-3OfxA symbolCell-3OfxA">
<div class="Name-3OfxA">Sophia</div>
</div>
<div class="cell-3OfxA descriptionCell-3OfxA">visited</div>
<div class="cell-3OfxA timeCell-3OfxA"><span>1/11/2022</span><span>12:10:00 AM</span></div>
</div>
<div class="bodyRow-3OfxA">
<div class="cell-3OfxA symbolCell-3OfxA">
<div class="Name-3OfxA">Luc</div>
</div>
<div class="cell-3OfxA descriptionCell-3OfxA">visited</div>
<div class="cell-3OfxA timeCell-3OfxA"><span>1/11/2022</span><span>12:40:02 AM</span></div>
</div>
<div class="bodyRow-3OfxA">
<div class="cell-3OfxA symbolCell-3OfxA">
<div class="Name-3OfxA">Daniel</div>
</div>
<div class="cell-3OfxA descriptionCell-3OfxA">status: unknown</div>
<div class="cell-3OfxA timeCell-3OfxA"><span>1/11/2022</span><span>12:32:02 AM</span></div>
</div>
<div class="bodyRow-3OfxA">
<div class="cell-3OfxA symbolCell-3OfxA">
<div class="Name-3OfxA">Michael</div>
</div>
<div class="cell-3OfxA descriptionCell-3OfxA">is blocked</div>
<div class="cell-3OfxA timeCell-3OfxA"><span>1/11/2022</span><span>12:49:02 AM</span></div>
</div>
<div class="bodyRow-3OfxA">
<div class="cell-3OfxA symbolCell-3OfxA">
<div class="Name-3OfxA">Vova</div>
</div>
<div class="cell-3OfxA descriptionCell-3OfxA">visited</div>
<div class="cell-3OfxA timeCell-3OfxA"><span>1/11/2022</span><span>3:02:01 PM</span></div>
</div>
</div>
</div>
Building a todo app in React, used filters but need a way to make sure “complete” button only removes one task instead of two
I’m new to learning react so I followed this tutorial https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components to create a todo app and then tweaked it to fit the requirements of the project I’m working on. Everything works the way it should except when I delete (complete) things from the associate side, it also deletes it from my main side as well. I understand the general concept of why that’s happening (I don’t have two separate lists in my code), just not sure how to go about fixing it without removing the filter I have in place. I had tried to implement a separate list for those tasks but just wasn’t understanding how to go about it.
App.js
const FILTER_MAP = {
All: () => true,
Associate: task => task.checked
};
const FILTER_NAMES = Object.keys(FILTER_MAP);
function App(props) {
const [tasks, setTasks] = useState(props.tasks);
const [filter, setFilter] = useState('All');
function toggleTaskChecked(id) {
const updatedTasks = tasks.map(task => {
if (id === task.id) {
return {...task, checked: !task.checked}
}
return task;
});
setTasks(updatedTasks);
}
function completeTask(id) {
const remainingTasks = tasks.filter(task => id !== task.id);
setTasks(remainingTasks);
}
const taskList = tasks
.filter(FILTER_MAP[filter])
.map(task => (
<Todo
id={task.id}
name={task.name}
checked={task.checked}
key={task.id}
toggleTaskChecked={toggleTaskChecked}
completeTask={completeTask}
/>
));
const filterList = FILTER_NAMES.map(name => (
<FilterButton
key={name}
name={name}
isPressed={name === filter}
setFilter={setFilter}
/>
));
function addTask(name) {
const newTask = { id: "todo-" + nanoid(), name: name, checked: false };
setTasks([...tasks, newTask]);
}
return (
<div className="app">
<h1 className = "tasks-header">Task Tracker</h1>
<Form addTask={addTask}/>
<div className="list-buttons">
{filterList}
</div>
<ul
role="list"
className="todo-list"
aria-labelledby="list-heading"
>
{taskList}
</ul>
</div>
);
}
export default App
Todo.js
export default function Todo(props) {
return (
<li className="todo stack-small">
<div className="c-cb">
<input id={props.id}
type="checkbox"
defaultChecked={props.checked}
onChange={() => props.toggleTaskChecked(props.id)}
/>
<label className="todo-label" htmlFor="todo-0">
{props.name}
</label>
</div>
<div className="btn-group">
<button type="button"
className="complete-button"
onClick={() => props.completeTask(props.id)}
>
Complete
</button>
</div>
</li>
);
}
index.js
const DATA = [
{ id: "todo-0", name: "Brush Teeth", checked: false },
{ id: "todo-1", name: "Make Dinner", checked: false },
{ id: "todo-2", name: "Walk Dog", checked: false },
{ id: "todo-3", name: "Run Reports", checked: false },
{ id: "todo-4", name: "Visit Mom", checked: false },
{ id: "todo-5", name: "Aerobics", checked: false },
{ id: "todo-6", name: "Project", checked: false },
{ id: "todo-7", name: "Lecture", checked: false },
{ id: "todo-8", name: "Have Lunch", checked: false }
];
ReactDOM.render(
<React.StrictMode>
<App tasks={DATA}/>
</React.StrictMode>,
document.getElementById('root')
);
FilterButton.js
function FilterButton(props) {
return (
<button
type="button"
className="toggle-btn"
aria-pressed={props.isPressed}
onClick={() => props.setFilter(props.name)}
>
<span className="visually-hidden">Show </span>
<span>{props.name}</span>
<span className="visually-hidden"> Tasks</span>
</button>
);
}
export default FilterButton;
How to get yup.string() to require string of any length greater than 3 or empty
i want to update a list of field data with formik.
i have this validation
validationSchema: Yup.object().shape({
password: Yup.string()
.min(4, 'Password must be at least 4 characters.')
.required('Password must be at least 4 characters.'),
....
}),
i want the user to be able to set password at least a length of 4 and if the user does not enter password then submit as empty string.
password component
<FormControl
fullWidth
error={Boolean(formik.touched.password && formik.errors.password)}
variant="outlined"
>
<InputLabel htmlFor="password">Password</InputLabel>
<OutlinedInput
id="password"
name="password"
inputProps={{
autoComplete: 'password',
form: {
autoComplete: 'off',
},
}}
type={showPassword ? 'text' : 'password'}
onBlur={formik.handleBlur}
onChange={formik.handleChange}
value={formik.values.password}
endAdornment={
<InputAdornment position="end">
<IconButton
aria-label="toggle password visibility"
onClick={() => setShowPassword(!showPassword)}
onMouseDown={(event) => event.preventDefault()}
edge="end"
>
{showPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
}
label="Password"
/>
{formik.errors.password && <FormHelperText>{formik.errors.password}</FormHelperText>}
</FormControl>
but with this code, if the password field is touched but not entered any password formik is not letting to submit the data. how can I do that? thank u in advance.
How to connect to a node js web server from another computer
Is there anyway to connect to a web server of node js from another computer that connected to same wifi?
i searched i get these results:
Connect to localhost:3000 from another computer | expressjs, nodejs
but all didnt worked can you help me? thanks