I’m asking for help in converting Javascript to Typescript.
How can I convert my code.
Here are my code.
const nodemailer = require(“nodemailer”);
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
I’m asking for help in converting Javascript to Typescript.
How can I convert my code.
Here are my code.
const nodemailer = require(“nodemailer”);
I have created a new React.js app using create-react-app.
For each component (e.g. src/components/ComponentX.js), I have created a separate stylesheet (src/styles/ComponentX.css), and imported it as follows import "../styles/ComponentX.css".
This has in turn resulted in a separate <style>...</style> section for each imported stylesheet on every page. Thus, the stylesheets are global (which makes sense for SPA?), albeit not concatenated as described here:
In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified .css file in the build output.
Since it doesn’t seem to affect the functionality of the React.js app, where stylesheets are imported, where should I import my stylesheets? Local to the components or in src/index.js?
Bonus: What about components sharing the same stylesheet? Should both import it, if following the local approach?
Let’s imagine I have to arrays:
const array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const array2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
array2.map((elem, index) => {
// Looking here to return the value from array1 by index
});
In array2 I am looking to return value from array1, by the index position, but just in range 1 -10. The idea is that it should go in a kind of circle where start value is 1 and end is 10.
More examples of how it should work:
I am using React-select Autocomplete search like the below screenshot. but I cannot collect input field value. there is no getting error or something. but I cannot type more than 1 letter after setState.
but only log this input value work log show porperly.
<AutoCompleteSearch
isLoading={isLoading}
options={filterOptions || []}
className='w-full mr-3'
onChange={(selectOption: any) => {
handleFilterOptionChange(selectOption)
}}
onInputChange={(inputValue: any) => {
console.log(event) //work properly
setSelectedKeyWord(inputValue) //after added this not work cannot type and not set state
}}
/>
in Storybook use component
import React, { FC, useState } from 'react'
import Select, { components } from 'react-select'
import CN from 'classnames'
export interface AutoCompleteSearchProps {
[x: string]: any
defaultValue?: { id: any; value: any; label: string | number }
isClearable?: boolean | true
isDisabled?: boolean
isLoading?: boolean | false
isMultiple?: boolean | false
isSearchable?: boolean | true
onChange?: any
onInputChange?: any
options: { id: any; value: any; label: string | number }[]
placeHolder?: string | 'Search'
value?: { id: any; value: any; label: string | number }
}
export const AutoCompleteSearch: FC<AutoCompleteSearchProps> = ({
className,
defaultValue,
isClearable,
isLoading,
isMultiple,
isSearchable,
onInputChange,
onChange,
options,
placeHolder,
value,
...restProps
}: AutoCompleteSearchProps) => {
const AutoCompleteSearchClasses = CN(`auto-complete-search`, className, {})
const [keyword, setKeyWord] = useState('')
function ValueContainer({ children, ...props }: any) {
return (
components.ValueContainer && (
<components.ValueContainer {...props}>
{!!children && (
<i
className='ri-search-line ri-lg text-N-500'
aria-hidden='true'
style={{ position: 'absolute', left: 14 }}
/>
)}
{children}
</components.ValueContainer>
)
)
}
const styles = {
valueContainer: (base: any) => ({
...base,
paddingLeft: 40,
}),
control: (base: any) => ({
...base,
'border': '1px solid #CCD6E1',
'borderRadius': '3px',
'boxShadow': '0px 1px 2px rgba(0, 45, 71, 0.05)',
'&:hover': {
border: '1px solid #CCD6E1',
},
'&:focus': {
border: '1px solid #3570AB',
boxShadow:
'0px 0px 4px rgba(0, 89, 141, 0.24), inset 0px 0px 4px rgba(0, 58, 89, 0.5)',
},
}),
menuPortal: (base: any) => ({ ...base, zIndex: 9999 }),
option: (base: any, { isFocused }: any) => ({
...base,
backgroundColor: isFocused ? '#EEF3F8' : '#fff',
color: '#2E3849',
}),
}
return (
<div className={AutoCompleteSearchClasses} {...restProps}>
<Select
components={{
ValueContainer,
DropdownIndicator: () => null,
IndicatorSeparator: () => null,
}}
defaultValue={defaultValue}
isClearable={isClearable}
isSearchable={isSearchable}
isLoading={isLoading}
isMulti={isMultiple}
options={options}
onChange={onChange}
onInputChange={onInputChange}
menuPosition='fixed'
placeholder={
<span className='select-placeholder-text text-N-500'>
{placeHolder}
</span>
}
styles={styles}
value={value}
/>
</div>
)
}
AutoCompleteSearch.defaultProps = {
defaultValue: undefined,
isClearable: true,
isSearchable: true,
isLoading: false,
isMultiple: false,
onChange: () => {},
onInputChange: () => {},
options: [],
placeHolder: 'Search',
value: undefined,
}
export default AutoCompleteSearch
exactly I want to catch React input type value and set it useState.
anyone can help me or can you guys know another method do this?
why am i getting this error message on my terminal that Missing ‘key’ prop for element in iterator

I have a file named check-rates that holds some useStates() that the users will input in order for me to execute and return for them an estimated value for their shipment by using DHL API.
In my nodejs express server, I am trying to access these useStates() with req.body but when I console log the constants I always get them as undefined. I need these values that the user enters so that the API becomes dynamic for each customer/user that uses my website and not fixed values (as I have them now.)
What am I doing wrong?
here is my code:
Check-Rates.js:
const [fromCountires,setFromCountries] = useState("");
const [fromCountriesCode,setFromCountriesCode] = useState("");
const [fromCountriesCapital,setFromCountriesCapital] = useState("");
const [fromPostalCode,setFromPostalCode] = useState("");
const [toCountries,setToCountries] = useState("");
const [toCountriesCode,setToCountriesCode] = useState("");
const [toCountriesCapital,setToCountriesCapital] = useState("");
const [weight,setWeight] = useState("");
const [data,setData] = useState(null);
const getRateEstimate = () => {
axios.get('http://localhost:3001/api/dhl').then(response => {
console.log(response)
setData(response.data);
}).catch(e => {
console.log(e)
});
}
return (
//example of how i am setting my needed useStates...
<Form.Group controlId="exampleForm.ControlInput1">
<Form.Label className={'fw-bold'}>Weight</Form.Label>
<Form.Control type="text" placeholder="" onChange={(e)=> {
setWeight(e.target.value)}}/>
</Form.Group>
<button className={'btn-orange fw-bold py-2 px-3 px-4 rounded getRateBtn'}
type={'submit'} onClick={getRateEstimate}> Check
</button>
)
NodeJS Server
index.js:
app.get('/api/dhl', (req, res) => {
const accountNum = req.body.accountNum
const fromCountriesCode = req.body.fromCountriesCode
const fromCountriesCapital = req.body.fromCountriesCapital
const toCountriesCode = req.body.toCountriesCode
const toCountriesCapital = req.body.toCountriesCapital
const weight = req.body.weight
const plannedShippingDate = req.body.date
const len = "5"
const width = "5"
const height = "5"
const isCustomsDeclarable = 'false'
const unitOfMeasurement = 'metric'
console.log(weight)//logs undefined
console.log(fromCountriesCapital)//logs undefined
var options = { method: 'POST',
url: 'https://express.api.dhl.com/mydhlapi/test/rates',
headers:
{ 'postman-token': '',
'cache-control': 'no-cache',
authorization: 'Basic AUTH',
'content-type': 'application/json' },
body:
{ customerDetails:
{ shipperDetails:
{ postalCode: '19010',
cityName: 'Dubai',//need this
countryCode: 'BH',//need this
addressLine1: '0' },//end Shipper DETAILS
receiverDetails:
{ postalCode: '76321',
cityName: 'Riyadh',//need this
addressLine1: '0',
countryCode: 'SA' }//end Reciever DETAILS
},
accounts: [ { typeCode: 'shipper', number: 'myAccountNumbeer' } ],
plannedShippingDateAndTime: '2021-08-25T13:00:00GMT+00:00',//need thiss
unitOfMeasurement: 'metric',
isCustomsDeclarable: true,
monetaryAmount: [ { typeCode: 'declaredValue', value: 10, currency: 'BHD' } ],
requestAllValueAddedServices: false,
returnStandardProductsOnly: false,
nextBusinessDay: false,
packages: [ { weight: 25, dimensions: { length: 5, width: 5, height: 5 } } ] },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
res.send(body)
console.log(body);
});
});
I am working on a React project with PostgreSQL database, this is the first time I am using it, and I am getting 42703 error on querying a particular column.
Below is the code I have written to query
const getList = (userId) => {
return new Promise(function (resolve, reject) {
pool.query(`SELECT items FROM public."user" where id=${userId}`, (error, results) => {
if (error) {
reject(error)
}
resolve(results);
})
})
}
I have defined this getList function and then I am making an api call to call this function by passing the userId like this
app.get(`/expenses`, verifySession(), async (req, res) => {
const userId = req.session.userId;
database.getList(userId)
.then(response => {
res.status(200).send(response);
})
.catch(error => {
res.status(500).send(error);
})
})
I even tried passing the userId directly as shown below , still it gives me the same error , which probably means I am querying in a wrong way
app.get(`/expenses`, verifySession(), async (req, res) => {
//const userId = req.session.userId;
database.getList('17a6dea6-a63e-4da7-9910-df7eddb672e6')
.then(response => {
res.status(200).send(response);
})
.catch(error => {
res.status(500).send(error);
})
})
Only when I directly write the string in the query it works properly like this
const getList = (userId) => {
return new Promise(function (resolve, reject) {
pool.query(`SELECT items FROM public."user" where id='17a6dea6-a63e-4da7-9910-df7eddb672e6'`, (error, results) => {
if (error) {
reject(error)
}
resolve(results);
})
})
}
Can someone please help we with what is exactly going wrong and if my syntax is correct or not ?
Is there any way by which I can use a feature- “slowly auto scroll to the bottom” when a visitor opens my website
(I want that when a visitor visits/open my website then the page should slowly start scrolling to the bottom)
If any way is there then please tell me
Can someone explain where my thinking goes wrong here ?
I have a class that adds a mousedown event listener to a specified canvas.
I make two instances of the class attached to two different canvases.
I expect to get responses from both instances but all responses say they’re from the second instance.
class Mycanvas{
constructor (canvas,name){
self = this;
this.name=name;
canvas.addEventListener('mousedown', mousedown);
}
function mousedown(){console.log(self.name)}
}
let mycanvas1 = Mycanvas(canvas1,'1');
let mycanvas2 = Mycanvas(canvas2,'2');
BUT, this code works fine :
class Mycanvas{
constructor (canvas,name){
this.name=name;
canvas.addEventListener('mousedown', ()=>console.log(this.name));
}
}
let mycanvas1 = Mycanvas(canvas1,'1');
let mycanvas2 = Mycanvas(canvas2,'2');
Let me clear the question suppose today is Thursday and I select Monday from the select dropdown then It will give the date of the upcoming Monday and If I select Saturday then It will give me the date of two days after means upcoming Saturday not a next week Saturday and so on.
how to check if a string includes all array elements, regardless of element’s position inside the string
for example:
var arr = ['lorem', 'ipsum', 'dolor'];
var str = 'lorem blue dolor sky ipsum';
I need something like this:
if(str.includesAll(arr)){console.log('string includes all elements');}
else{console.log('string does not include all elements');}
Suppose I click on a html element that isn’t in an array, and I want to know its index. For example the index of a h1 element. How do I get that with JavaScript?
I try to implement Alpine JS within a existing page.
For that, I’m using the CDN version of Alpine, which I’m loading within my :
<script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>
Now I’m trying to access Alpine from a custom.js file, which is loaded automatically within the footer of my page:
Alpine.magic('post', function () {
return function (url, data = {}) {
return fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
body: JSON.stringify(data)
});
}
});
Within my content I tried this:
<div x-data>
<h1>Alpine Test</h1>
<button type="button" @click="$post('/api/users', { name: 'John Doe' })">Add user</button>
</div>
By clicking the button, this error occurs:
Uncaught ReferenceError: $post is not defined
I’ve also tried it with window.Alpine, without success.
How can I add magic properties and stuff like that without using modules?
const { ApolloServer, gql } = require('apollo-server-express');
const express = require('express');
const port = process.env.PORT || 4000;
const notes = [
{ id: '1', content: 'This is a note', author: 'Adam Scott' },
{ id: '2', content: 'This is another note', author: 'Harlow Everly' },
{ id: '3', content: 'Oh hey look, another note!', author: 'Riley Harrison' }
];
const typeDefs = gql `
type Note {
id: ID
content: String
author: String
}
type Query {
hello: String
notes: [Note]
note(id: ID!): Note
}
type Mutation {
newNote(content: String!): Note
}
`;
const resolvers = {
Query:{
hello: () => 'Hello World',
notes: () => notes,
note: (parent, args) => {
return notes.find(note => note.id == args.id);
},
Mutation: {
newNote: (parent, args) => {
let noteValue = {
id : String(notes.length + 1),
content : args.content,
author: 'Adam Scott',
};
notes.push(noteValue);
return noteValue;
}
}
},
}
Some people had naming issues but seems that I’m using the same in resolver as well as in schema.
Please bare with me, this is my second day in GraphQL and Express. I removed intentionally imports and assignment of express object, middleware since it does not let me post.
I’ve searched and searched but I’ve only found solutions to .join() the items into a single string..this is my first question so I’ll try my best to explain thoroughly.
const createCard = () => {
const pokemonTypes = ['grass', 'fire', 'water'];
return (
`<div>
${pokemonTypes.map(type => `<div>${type}</div>`)}
</div>`
)
}
document.body.insertAdjacentHTML("beforeend", createCard());
For some context, I am using an API but I simplified the code so it’s quick and easy to read.
I am trying to display each string into its own div so that I can style each div separately…like color coded buttons: green for grass, blue for water, red for fire etc.
When I run the code the strings successfully display in their own div, however the comma remains. I’d like them to just display next to each without the comma separating them.
Thank you!