I would like integrate Ozon vendor and fire this vendor in Geo Location in UK side. Please can you help me how to perform it? How i should prevent ozon ads request in UK zone
Category: javascript
Category Added in a WPeMatico Campaign
Mirage JS json data is console logging but not rendering on the page in React
I am working on a coding assessment and running into a problem when it comes to rendering dummy data from Mirage JS on my page. When I console log the data I’m looking for it shows up fine in the console but I can’t figure out why it’s not rendering on the page.
Here’s the server.js
import { createServer, Model } from "miragejs";
import faker from "faker";
import avatar from "./avatar.png";
export function makeServer({ environment = "test" } = {}) {
let server = createServer({
environment,
models: {
employee: Model,
},
seeds(server) {
for (let i = 0; i < 10; i++) {
server.create("employee", {
id: faker.datatype.uuid(),
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
email: faker.internet.email(),
phone: faker.phone.phoneNumber(),
bio: faker.lorem.paragraph(),
avatar: avatar,
address: {
streetAddress: `${faker.address.streetAddress()} ${faker.address.streetName()}`,
city: faker.address.city(),
state: faker.address.stateAbbr(),
zipCode: faker.address.zipCode(),
},
});
}
},
routes() {
this.namespace = "api";
this.get(
"/employees",
(schema) => {
return schema.employees.all();
},
{ timing: 1000 }
);
this.patch(
"/employees/:id",
(schema, request) => {
const attrs = JSON.parse(request.requestBody);
const employee = schema.employees.find(request.params.id);
employee.update(attrs);
},
{ timing: 300 }
);
this.delete(
"/employees/:id",
(schema, request) => {
const employee = schema.employees.find(request.params.id);
employee.destroy();
return new Response();
},
{ timing: 300 }
);
},
});
return server;
}
and here’s the app.js
import { makeServer } from "./server";
import { useEffect, useState } from "react";
if (process.env.NODE_ENV === "development") {
makeServer({ environment: "development" });
}
function App() {
const [employees, setEmployees] = useState([])
useEffect(() => {
fetch('/api/employees')
.then(res => res.json())
.then(json => setEmployees(json.employees)
)
}, [])
return (
<div>
<header>
<h1>Employees</h1>
</header>
{employees.length > 0 ? (
<table>
<thead>
<tr>
<th>id</th>
<th>first name</th>
<th>last name</th>
</tr>
</thead>
<tbody>
{employees.map(({id, firstName, lastName}) => {
<tr key={id}>
<td>{id}</td>
<td>{firstName}</td>
<td>{lastName}</td>
</tr>
console.log(firstName)
})}
</tbody>
</table>
) : (
<p>No employees</p>
)}
</div>
);
}
export default App;
Scroll to top when using pagination in React
I am loading data card and when I press pagination buttons, the data changes but screen remains in the same place. How do I scroll to top when button is pressed? The application is a SPA so maybe that is causing the issue?
Best way to Search ALL Terms in Array of Objects
I’m trying to filter out objects based on whether ALL the given search terms exist in SOME of the property values of EACH object in the array.
But I also don’t want to search within the deviceId
property.
But is there a way to do it with less code?
So I do the following:
- Convert the objects into iterable arrays
- Filter out the array to remove arrays with
deviceId
- Convert the arrays back into the Key/Value pair objects
let DeviceDtoArrayOfArray = [];
DeviceDtos.forEach((indiv) => {
DeviceDtoArrayOfArray.push(Object.entries(indiv));
});
let DeviceDtoArrayOfArrayFiltered = [];
DeviceDtoArrayOfArray.forEach((indiv) =>
DeviceDtoArrayOfArrayFiltered.push(
indiv.filter((indiv) => indiv[0] !== "deviceId")
)
);
let DeviceDtoArrayOfArrayFilteredObjects = [];
DeviceDtoArrayOfArrayFiltered.forEach((indiv) => {
DeviceDtoArrayOfArrayFilteredObjects.push(Object.fromEntries(indiv));
});
- Define sample search term array
- For each object from Step 3, create an array of it’s property values
- Filter each Object in the array by searching each Search Term, check to see if it exists within some of the property values from Step 5, if it exists, then the object is returned to a new array, if not, it’s filtered out
Sample Array containing the objects with deviceId
const DeviceDtos = [
{
deviceId: 1,
deviceName: "Device0000",
hwModelName: "Unassigned",
deviceTypeName: "Unassigned",
serviceTag: "A1A"
},...
Sample Search Terms
const searchTerms = ["HwModel", "A1A"];
Filter out objects based on Search Terms
const results = DeviceDtoArrayOfArrayFilteredObjects.filter((indiv) => {
const propertiesValues = Object.values(indiv); // all property values
return searchTerms.every((term) =>
propertiesValues.some(
(property) => property.toLowerCase().indexOf(term.toLowerCase()) > -1
)
);
});
console.log(results);
Create a styling rule for clsx for React + Typescript
Having this clsx method which works fine:
const getLinkClasses = (disabled: boolean) => {
return clsx('flex whitespace-nowrap', {
'text-gray-500': !disabled,
'text-gray-300 cursor-not-allowed': disabled
});
};
There are two other optional variables, one for disabled and one for !disabled that are strings and can add new rules to the above method. Let’s call them disabledValue
and notDisabledValue
.
For example,
const disabledValue = 'bg-red-100';
const notDisabledValue = 'bg-green-100';
In order to add those variables, I’ve made the following changes:
export interface MyProps {
disabledValue?: string;
notDisabledValue?: string;
}
const getLinkClasses = (disabled: boolean, style: MyProps) => {
const notDis = `text-gray-500 ${style.notDisabledValue ?? ''}`;
const dis = `text-gray-300 cursor-not-allowed ${style.disabledValue ?? ''}`;
return clsx('flex whitespace-nowrap', {
notDis: !disabled,
dis: disabled
});
};
The problem is that those two variables, notDis
and dis
aren’t read:
‘notDis’ is declared but its value is never read.ts(6133)
‘notDis’ is assigned a value but never
used.eslint@typescript-eslint/no-unused-vars
Is there a way to fix it?
Pass Javascript Array containing multiple files to PHP
I would like to send Javascript array containing files to PHP using AJAX
The following are 3 files that I want to send to the php side. (These outputs come from console.log(document.getElementById("id").files[0]
);
File { name: "img1.svg", lastModified: 1641853737982, webkitRelativePath: "", size: 2506, type: "image/svg+xml" }
File { name: "img2.svg", lastModified: 1641853677323, webkitRelativePath: "", size: 1060, type: "image/svg+xml" }
File { name: "img3.svg", lastModified: 1641853656789, webkitRelativePath: "", size: 1845, type: "image/svg+xml" }
In this case there are 3 files (There can be more or less than that).
The 3 files are in a variable arrFiles
.
So console.log(arrFiles) outputs:
Array [ File, File, File]
JQuery file
var form_data = new FormData();
var arrFiles = JSON.stringify(arrFiles)
form_data.append("imgs", arrFiles);
$.ajax({
url:url,
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success:function(data)
{
alert(data);
}
});
php file
if(isset($_POST["imgs"])){
//Would like to handle each image separately.
$imgs = json_decode($_POST['imgs']);
//May be something like :
foreach($_POST["imgs"] as $img){
$movePath = "images/".$img['name'];
move_uploaded_file($img["tmp_name"], $movePath);
}
return;
}
Is there a way to handle this ?
Proper way to sanitize external urls to insert into database [JavaScript, PHP]
I am trying to implement a function that allows users to input any URL they would like to their home screen on my website.
Is there a proper way to sanitize URL links before inserting to a database?
Thank you in advance!
SMTP mails going to spam folder
I am using JavaScript to automate sending emails on my website, with SMTP and a gmail email address however the emails are sent directly to the receivers spam folder. Is there a way around this?
Here is my code:
function sendEmail() {
Email.send({
Host: "smtp.gmail.com",
Username: "[email protected]",
Password: "pass",
To: document.getElementById('email').value,
From: "[email protected]",
Subject: "Subject",
Body: "hooray",
})
.then(function (message) {
alert("mail sent successfully")
});
}
Is there an efficient way to show images based on a route and file name using javascript?
Right now I have something like
const route = '/Images/Banner/'
const slides = [
{
name: "banner-01",
url: `${route}banner-01.png`
},
{
name: "banner-02",
url: `${route}banner-02.png`
},
{
name: "banner-03",
url: `${route}banner-03.png`
},
]
]
In this, I’m manually adding each image and it’s properties because there are only 3 images, but i want to dynamically add them based on the quantity of images with the same name (they’ll always are going to be named banner-NN).
Is there an efficient way to iterate through images with the same pattern of name (‘banner-‘) and place them in an array of objects?
rtl in material ui cause ruined my app appearance
i setuped mui rtl configuration step by step in v5mui. using emotion as styled-engine
stylis v4
stylis-plugin-rtl v2
every thing is ok but when using some complicated component my app apearance crash.
there are a warning in terminal that i think it will be the answere…
but i dont understand it.
enter code here
WARNING in ./node_modules/stylis-plugin-rtl/dist/stylis-rtl.js Module Warning (from ./node_modules/source-map-loader/dist/cjs.js): Failed to parse source map from '/home/hamid/Desktop/zahra/node_modules/stylis-plugin-rtl/src/stylis-rtl.ts' file: Error: ENOENT: no such file or directory, open '/home/hamid/Desktop/zahra/node_modules/stylis-plugin-rtl/src/stylis-rtl.ts' @ ./src/index.js 8:0-42 15:18-27
How to move blinking element after javascript result?
I’m trying to move my blinking element directly to end of the result in the same line.
But my blinking cursor still shows under my javascript result and I can’t put it on the end of the result.
I tried: flex, float left, display: inbolcks and even margin div into div, but id didn’t help.
How can I do it?
I will be really glad for help!
function myFunction()
{
result.innerHTML += "I will not make any more boring art ";
}
body
{
background-color:white;
font-family: Lucida Console Regular;
font-size:15px;
color:black;
border-width:0px;
border: 0;
}
input {
font-size:15px;
border-top-style: hidden;
border-right-style: hidden;
border-left-style: hidden;
border-bottom-style: hidden;
background-color: white;
font-family: Lucida Console Regular;
color: transparent;
display: inline-block;
}
result{
display: flex;
}
.no-outline:focus {
outline: none;
}
textarea:focus, input:focus{
outline: none;
}
.cursor {
position: relative;
float:left;
flex:1;
}
.cursor i {
flex:1;
position: absolute;
width: 1px;
height: 100%;
background-color: black;
animation-name: blink;
animation-duration: 800ms;
animation-iteration-count: infinite;
opacity: 1;
}
@keyframes blink {
from { opacity: 1; }
to { opacity: 0; }
}
<input class="class" type="text" onkeydown="myFunction()" placeholder="type something" autofocus spellcheck="false" >
<div id="result"></div>
<div class="cursor">
<input type="text" class="rq-form-element" /><i></i></div>
How can I list all member roles from top to bottom? discord.js
I have this code for list all member roles but it’s not in list from top to bot
member.roles.cache.map((r) => r).slice(0,-1)
I want something like this
How to dynamically resize the image in html
I am making a text editor using basic html, css and javascript, I want to add a functionality for the user to resize the image after uploading it, like we do in MS Word.
I searched this several times but I didn’t get the result.
I tried to tackle this problem by making a resizable div and putting the image in this div, by setting the height and width of image 100% according to the div. Now, I can resize the image by resizing the div. But, the problem here is, user can write in this div also and i don’t want that, if i set contenteditable = “false” for this div then user can’t delete this image.
So, is there a way to dynamically resize the image in html using basic css and js.
Jest TypeError: Cannot destructure property ‘enqueueSnackbar’ of ‘(0 , _notistack.useSnackbar)(…)’ as it is undefined
I have a Jest unit test that is testing an error from a mocked API call to ensure that the error message is displayed on the page. In my actual file, I’m using notistack
to display the error messages. I’ve not displayed the full API request because I don’t think it’s relevant so in short, it is the following:
myComponent.js:
import { useSnackbar } from 'notistack';
const myComponent = props => {
const { enqueueSnackbar } = useSnackbar()
//make an API call to an endpoint
...
if (response.ok) enqueueSnackbar("API Success", { variant: "success" });
else enqueueSnackbar("API Failed", { variant: "error" });
}
As a result of this, I am testing the above on my unit test. Again, I won’t paste the whole unit test because I don’t think it’s relevant, but something similar to:
myComponent.test.js
import { render, screen } from "@testing-library/react"
test('testing error message on API call", async () => {
// mock the API call to return a 500 <- this works fine
// ensure that the error message is displayed in the screen
expect(screen.queryByText(/API Failed/)).toBeInTheDocument();
});
Doing the above, I get an error:
TypeError: Cannot destructure property ‘enqueueSnackbar’ of ‘(0 ,
_notistack.useSnackbar)(…)’ as it is undefined
If I simply include something like the following, enqueueSnackbar()
will be defined but the test still fails because the message is null
.
const mockEnqueue = jest.fn();
jest.mock('notistack', () => ({
...jest.requireActual('notistack'),
useSnackbar: () => {
return {
enqueueSnackbar: mockEnqueue
};
}
}));
However, I don’t even want to mock the snackbar because I want to test the actual display message for each specific scenario (there are multiple).
How to add information pop-up for TextInput in React Native?
I want to achieve something like this in React Native:
I have a TextInput component and I want to put an icon to the right side. The user can click it, then I can display some text in a modal or in a another component.
Is this possible in react native?
return(
<View style={styles.container}>
<TextInput
placeholder="Állat neve"
value={AllatNev}
style={styles.textBox}
onChangeText={(text) => setAllatNev(text)}
/>
</View>
);
}
)
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: color_theme_light.bodyBackground
justifyContent: 'center',
alignItems:'center'
},
textBox:{
borderWidth:2,
borderColor: color_theme_light.textBoxBorder,
margin:15,
borderRadius:10,
padding: 10,
fontFamily:'Quicksand-Medium'
},
});