i used called maotu third-party lib [enter link description here][1] ,There are two features I don’t need. I modified the source code, but it doesent’t work.Specifically, on the page of the webtopoEdit path, there will be an icon and a help button。I commented out almost all the code for these two functions but they are still there. please help me。
Category: javascript
Category Added in a WPeMatico Campaign
Is it possible to conditionally skip assertions in playwright tests?
I would like to avoid adding the same if condition with assertion in different tests. Example:
if (flag === true) {
expect(1+1, "Adding two ones.").toBe(2);
}
Is there a way to build the if condition in a central place and reuse, maybe like a custom matcher?
How to enable pinch zoom on mobile after requestFullscreen?
I’m trying to use requestFullscreen() functionality of Javascript and it looks like it disables pinch zoom when on mobile. Is there a way to enable it, I’ve looked for it but I did’t found any solution.
Here’s an example.
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=12.0, minimum-scale=.25, user-scalable=yes"/>
</head>
<body>
<div id="container" style="background-color: white;">
<button onclick="fullscreen()">Click here</button>
<p id="message">Example</p>
</div>
<script>
function fullscreen() {
document.getElementById('container').requestFullscreen();
}
</script>
</body>
</html>
Run a backend server upon start in electron app
I have an electron app (created using electron forge) that uses Flask (python) for the backend. I’d like to start the whole application (flask and electron) from electron itself by starting a child process in main.js. Starting the flask process doesn’t work in the production build (the resulting app from npm run make), as I’m getting a Failed to load resource: net::ERR_CONNECTION_REFUSED in my console.
This is my main.js:
const { app, BrowserWindow } = require('electron');
const path = require('path');
const { spawn } = require('child_process');
let mainWindow;
let flaskProcess;
const createWindow = () => {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 1000,
height: 800,
webPreferences: {
preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
},
});
// and load the index.html of the app.
console.log(MAIN_WINDOW_WEBPACK_ENTRY)
mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY);
// const src = path.join(path.dirname(path.dirname(__dirname)), 'src')
// mainWindow.loadFile(`./src/index.html`);
// Open the DevTools.
mainWindow.webContents.openDevTools();
};
app.on('ready', () => {
// Start the Flask server
const py_exec = '/Users/brianbarry/Desktop/computing/visual-shell/backend/venv/bin/python'
const server_entry = '/Users/brianbarry/Desktop/computing/visual-shell/backend/run.py'
flaskProcess = spawn(py_exec, [server_entry]);
flaskProcess.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
flaskProcess.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
flaskProcess.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
// Wait a bit for the server to start
setTimeout(createWindow, 3000);
});
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', function () {
if (mainWindow === null) {
createWindow();
}
});
app.on('will-quit', () => {
if (flaskProcess) {
flaskProcess.kill();
}
});
Re-render modal component onClick with random value parameters
i’m new to ReactJS. And I’m trying to create an app which displays a modal with different parameters. My problem is, I have a reusable modal component, but how do I achieve when pressing/clicking a button inside the modal will re-render the whole modal component with different results/value?
Here is my code:
Modal.js
import { useEffect, useRef, Fragment, Link, useState } from "react";
import { useParams, useNavigate, useLocation } from "react-router-dom";
import { disableBodyScroll, enableBodyScroll } from "body-scroll-lock";
import airportData from '../airports.json';
export function Modal() {
const modalRef = useRef();
const { id } = useParams();
const navigate = useNavigate();
const [reload, setReload] = useState(false);
useEffect(() => {
const observerRefValue = modalRef.current;
disableBodyScroll(observerRefValue);
return () => {
if (observerRefValue) {
enableBodyScroll(observerRefValue);
}
};
}, []);
function setImageUrlLarge(url) {
return {
backgroundImage: `url(${process.env.PUBLIC_URL}/assets/images/large/${url}.jpg)`
}
}
return (
<div ref={modalRef} className="modal-wrapper">
<div className="modal">
<div className={`detail ${id} overlay`} style={setImageUrlLarge(id)}>
<a className='overlay' rel='noopener'></a>
<AirportDetails id={id} airportData={airportData} />
</div>
</div>
</div>
)
function AirportDetails({id, airportData}) {
const [data, setData] = useState(airportData);
const [airportId, setAirportId] = useState(id);
const airport = airportData.filter((airport) => airport.id.toLowerCase().includes(id.toLowerCase()))[0];
const [description, setDescription] = useState(airport.description);
const pattern = /*([A-Za-z])*/gi;
const em = description.replace(pattern, '<em>$1</em>');
const currUrl = window.location.href;
function capitalize(str) {
return str.toUpperCase();
}
const share = (socialType) => e => {
if (socialType == "twitter") {
const text = `Making sense of those three-letter airport codes: ${capitalize(id)}`;
const link = `https://twitter.com/intent/tweet?url=${currUrl}&text=${text}`;
return link;
}
const link = `https://www.facebook.com/dialog/share?display=popup&href=${currUrl}${id}&redirect_uri=${currUrl}${id}`;
return link;
}
function setTo(social) {
if(social=="twitter") {
return "https://twitter.com/intent/tweet?url=$SHARE_URL&text=$TEXT";
}
else {
return "https://www.facebook.com/sharer/sharer.php?u=$SHARE_URL";
}
}
return (
<div className='container'>
<div className='detail-info'>
<h1>{airport.id}</h1>
<h2>{airport.name}</h2>
<h3><span className="local_name">{airport.local_name}</span></h3>
<h4>{airport.city}</h4>
<div className="description fl-edu">
<p dangerouslySetInnerHTML={{ __html: em}}></p>
</div>
<a className="close-detail" role="button" onClick={() => navigate('/')}></a>
<a className="random" role="button" onClick={() => {randomAirport()}}>
Random Airport</a>
<div className="social">
<a role="button" className="twitter" href={setTo("twitter")} onClick={() => {share("twitter")}} target="_blank"></a>
</div>
<div className="social">
<a className="facebook" href={setTo("facebook")} onClick={() => {share("facebook")}} target='_blank'></a>
</div>
</div>
<div className="photo-credit">
Photo by <a>{airport.imageCredit}</a>
</div>
<a className="back" role="button" onClick={() => navigate('/')}>Airport Codes PH</a>
</div>
)
}
function randomAirport() {
const rand = Math.floor(Math.random() * airportData.length);
const airportRandData = airportData[rand];
setReload(!reload);
console.log(reload);
}
}
What i’m achieving right now is to change the state of the modal every time when the button is clicked and randomizing the value of an object. I’m expecting to reload the modal component with a different value from the randomAirport function and passing the airportData back to the Modal component.
How to distinguish requests made by javascript vs requests made without javascript?
I have a form:
<form action="/login" method="post" id="loginForm">
<input type="email" name="email" id="emailInput">
<input type="password" name="password" id="passwordInput">
<button type="submit">Log In</button>
</form>
And I wish for my server to respond to submissions of this form with JSON.
router.post("/login", (req, res) => {
user = logIn(req.body.email, req.body.password);
if (user) {
res.status(200).json({ user: user });
}
else {
res.status(401).json({ user: null });
}
});
However, if this request is sent by the browsers native submission process, the browser will just end up rendering the JSON object which is not ideal so I have to use this javascript for it to work:
const loginForm = document.getElementById("loginForm");
const emailInput = document.getElementById("emailInput");
const passwordInput = document.getElementById("passwordInput");
loginForm.addEventListener("submit", (e) => {
e.preventDefault();
const formData = new FormData();
formData.append("email", emailInput.value);
formData.append("password", passwordInput.value);
const result = await fetch("/login", {
method: "POST",
body: formData,
}).then(res => res.json())
// handle result ...
});
This works fine, however, if the user has javascript disabled, the browser will still end up sending the form and render the JSON object as the response. Since I cant seem to find any way to fully disable the form if javascript is disabled, I want to detect if the form was submitted by javascript or not so that I can redirect the user to a “please enable javascript” page instead. Is there a way to check for this regardless of which browser is used ect. so I always know if I am dealing with a javascript request or not?
(My application will require javascript for almost all its functionality so I am not interested in making propper no-js alternatives for every single one of my routes.)
Send event from Google Spreadsheet to a Chrome extension
I previously had a Google Spreadsheet where I was able to send an event with parameters to my Google Chrome extension. It was a bit of a hack but the cell in my spreadsheet had something like this –
=HYPERLINK(CONCATENATE("#gid=12345678&player=", ENCODEURL(C3), "&team=", D3), "chrome")
Clicking on this link would edit the URL of the current tab, and in my Chrome ext I had something like this in my background.js file –
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (tab.url.match(/google.com/spreadsheets/g)) {
console.log(tab.url);
}
}
This method worked fine for a couple years, but recently Google must’ve started blocking URL manipulation from within spreadsheets and this broke the message passing hack I had in place. I tried using a content script to place an event listener on the =HYPERLINK() output in the spreadsheet, but Google Spreadsheet outputs the entire DOM onto a canvas so I’m unable to drill down and find the hyperlink element.
Does anyone know of a better workaround for my use case?
unexpected token (…) for no reason [closed]
This entire HTML’s script code:
[...document.querySelectorAll("input")].forEach(ele => {
ele.addEventListener(
"change", () => {
Main();
}
);
});
function Main() {
document.getElementById("Output").textContent = ""
[...document.querySelectorAll("*.HiddenMsg")].forEach(ele => ele.hidden = true)
try {
let DatesWrong = false
let StartDate = new Date(document.getElementById("Input_DateTimeStart").value)
if (StartDate.toString() == "Invalid Date") {
document.getElementById("Input_DateTimeStart_ErrorMsg").hidden = false
DatesWrong = true
}
let EndDate = new Date(document.getElementById("Input_DateTimeEnd").value)
if (EndDate.toString() == "Invalid Date") {
document.getElementById("Input_DateTimeEnd_ErrorMsg").hidden = false
DatesWrong = true
}
if (DatesWrong) {
return
}
let TimeDiff = EndDate.valueOf() - StartDate.valueOf()
if (TimeDiff < 0) {
document.getElementById("Output").textContent = "End date before start."
return
}
let DurationString = DisplayTimeDuration(TimeDiff)
document.getElementById("Output").textContent = "Duration: " + DurationString + " (" + TimeDiff.toFixed(0) + " ms)"
} catch {
return
}
}
function DisplayTimeDuration(Duration) {
let OutputString = ""
Duration = Math.abs(Duration)
let UnitsOfTimeArray = []
let Seconds = Math.floor(Duration/1000)
UnitsOfTimeArray.unshift({Unit: Seconds % 60, UnitName: "s"})
let Minute = Math.floor(Seconds/60)
UnitsOfTimeArray.unshift({Unit: Minute % 60, UnitName: "m"})
let Hour = Math.floor(Minute/60)
UnitsOfTimeArray.unshift({Unit: Hour % 24, UnitName: "h"})
let Day = Math.floor(Hour/24)
UnitsOfTimeArray.unshift({Unit: Day, UnitName: "d"})
let LeadingUnitIsNonZero = false
for (let i = 0; i < UnitsOfTimeArray.length; i++) {
if (UnitsOfTimeArray[i].Unit != 0) {
LeadingUnitIsNonZero = true //Once it's true, stays true. All remaining units are significant
}
if (LeadingUnitIsNonZero || i == UnitsOfTimeArray.length-1) {
OutputString += UnitsOfTimeArray[i].Unit + UnitsOfTimeArray[i].UnitName
if (i != UnitsOfTimeArray.length-1) {
OutputString += " "
}
}
}
return OutputString
}
The code [...document.querySelectorAll("*.HiddenMsg")].forEach(ele => ele.hidden = true), for whatever reason, errors out saying Uncaught SyntaxError: Unexpected token '...', however, when I change that line of code to have a identifier like this: let test = [...document.querySelectorAll("*.HiddenMsg")].forEach(ele => ele.hidden = true), it works fine. Any idea why this bug false-positively say there’s a syntax error with the spread syntax? The very literal first line of code have no issues whatsoever.
Discord.js Auto Register Slash Commands
Trying to build an index.js file that auto loads, auto reloads, and disables modules with errors in them to prevent the bot from crashing. This portion is working fine.
One of the modules that is loading is registerCommands.js where I am trying to auto register all slash commands that can be found in the various auto loaded modules.
I’ve been trying to figure this out for days so if someone could give me a bit of an understanding as to what I’ve done wrong here.
Index.js
const fs = require('fs');
const path = require('path');
const chokidar = require('chokidar');
const {
Client,
GatewayIntentBits,
ActivityType,
EmbedBuilder,
ActionRowBuilder,
ButtonBuilder,
SlashCommandBuilder,
PermissionFlagsBits,
ModalBuilder,
TextInputBuilder,
TextInputStyle,
PermissionsBitField,
ChannelType,
Events,
Partials,
StringSelectMenuOptionBuilder
} = require('discord.js');
let config = require('./config.js');
let guildConfig = require('./guildConfig.js'); // New addition
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildBans,
GatewayIntentBits.GuildEmojisAndStickers,
GatewayIntentBits.GuildIntegrations,
GatewayIntentBits.GuildWebhooks,
GatewayIntentBits.GuildInvites,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildMessageTyping,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.DirectMessageReactions,
GatewayIntentBits.DirectMessageTyping,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildScheduledEvents
],
partials: [Partials.Channel]
});
const ADMIN_CHANNEL_ID = '0000'; // Replace with your specific channel ID in the admin guild
let logChannel = null;
const modules = new Map();
const getTimeStamp = () => {
const now = new Date();
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');
return `${hours}:${minutes}:${seconds}`;
};
const logMessage = async (message) => {
const timestampedMessage = `[${getTimeStamp()}] ${message}`;
originalConsoleLog(timestampedMessage); // Log to console
if (logChannel) {
try {
await logChannel.send(````jsn${timestampedMessage}n````);
} catch (error) {
originalConsoleLog(`[${getTimeStamp()}] Error sending log message to Discord:`, error);
}
} else {
originalConsoleLog(`[${getTimeStamp()}] Log channel not found. Unable to send log: ${message}`);
}
};
// Override console.log to use logMessage function
const originalConsoleLog = console.log;
console.log = async (...args) => {
const message = args.join(' ');
await logMessage(message);
};
const initializeLogChannel = async () => {
try {
const guild = await client.guilds.fetch(config.adminGuild);
logChannel = await guild.channels.fetch(ADMIN_CHANNEL_ID);
if (!logChannel) {
await logMessage(`Channel with ID ${ADMIN_CHANNEL_ID} not found in guild ${config.adminGuild}`);
}
} catch (error) {
await logMessage(`Error fetching guild or channel: ${error.message}`);
}
};
const loadModule = async (filePath) => {
try {
// Attempt to unload the module if it exists
await unloadModule(filePath);
delete require.cache[require.resolve(filePath)];
const module = require(filePath);
if (typeof module === 'function') {
module(client, { config, guildConfig }); // Pass config and guildConfig to the module
await logMessage(`Loaded module: ${filePath}`);
modules.set(filePath, module);
}
} catch (error) {
await logMessage(`Error loading module ${filePath}: ${error.message}`);
await logMessage(`Unloaded module due to error: ${error.message}`);
}
};
const unloadModule = async (filePath, error = null) => {
if (modules.has(filePath)) {
try {
const module = modules.get(filePath);
if (module.unload) {
module.unload(client);
}
delete require.cache[require.resolve(filePath)];
modules.delete(filePath);
let message = `Unloaded module: ${filePath}`;
if (error) {
message += ` due to error: ${error.message}`;
}
await logMessage(message);
} catch (unloadError) {
await logMessage(`Error unloading module ${filePath}: ${unloadError.message}`);
}
}
};
const loadModules = async (dir) => {
try {
const files = fs.readdirSync(dir);
for (const file of files) {
const filePath = path.join(dir, file);
if (fs.statSync(filePath).isDirectory()) {
await loadModules(filePath);
} else if (file.endsWith('.js')) {
await loadModule(filePath);
}
}
} catch (error) {
await logMessage(`Error loading modules from directory ${dir}: ${error.message}`);
}
};
client.once('ready', async () => {
await logMessage(`Logged in as ${client.user.tag}!`);
client.user.setActivity('Being built!', { type: ActivityType.Watching });
await initializeLogChannel();
// Load all modules from the ./bot-modules/ directory
await loadModules(path.join(__dirname, 'bot-modules'));
// Load and execute the register commands module
require('./bot-modules/registerCommands')(client);
// Start the watcher after loading all modules
const watcher = chokidar.watch(path.join(__dirname, 'bot-modules'), {
ignoreInitial: true
});
watcher.on('all', (event, filePath) => {
if (filePath.endsWith('.js')) {
if (event === 'change' || event === 'add') {
console.log(`Reloading module: ${filePath}`);
loadModule(filePath);
} else if (event === 'unlink') {
console.log(`Removing module: ${filePath}`);
unloadModule(filePath);
}
}
});
// Watch the config.js and guildConfig.js files for changes
const configWatcher = chokidar.watch([path.join(__dirname, 'config.js'), path.join(__dirname, 'guildConfig.js')], {
ignoreInitial: true
});
const reloadConfigs = async (filePath) => {
const configName = path.basename(filePath);
console.log(`Reloading ${configName}`);
delete require.cache[require.resolve(filePath)];
if (configName === 'config.js') {
config = require('./config.js');
await logMessage(`Configuration reloaded: ${configName}`);
} else if (configName === 'guildConfig.js') {
guildConfig = require('./guildConfig.js');
await logMessage(`Configuration reloaded: ${configName}`);
}
};
configWatcher.on('change', reloadConfigs);
});
client.login(config.token);
registerCommands.js
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const fs = require('fs');
const path = require('path');
module.exports = async (client) => {
const commands = [];
client.commands = new Map();
try {
// Load command files
const commandFiles = fs.readdirSync(path.join(__dirname)).filter(file => file.endsWith('.js') && file !== 'registerCommands.js');
for (const file of commandFiles) {
console.log(`Loading command file: ${file}`);
const command = require(path.join(__dirname, file));
if (command.data && command.execute) {
commands.push(command.data.toJSON());
client.commands.set(command.data.name, command);
console.log(`Loaded command: ${command.data.name}`);
} else {
console.warn(`Skipping file: ${file} (missing data or execute)`);
}
}
} catch (error) {
console.error('Error loading commands:', error);
}
const rest = new REST({ version: '10' }).setToken(client.token);
client.once('ready', async () => {
try {
console.log('Started refreshing application (/) commands.');
// Register commands for the guilds specified in the config
const { adminGuild, memberGuild } = require('./config.js');
const guildIds = [adminGuild, memberGuild];
for (const guildId of guildIds) {
// Register commands in the guild
await rest.put(
Routes.applicationGuildCommands(client.user.id, guildId),
{ body: commands }
);
console.log(`Successfully reloaded application (/) commands for guild ${guildId}.`);
// Log the registered commands
console.log('Registered commands:');
commands.forEach(cmd => console.log(`- ${cmd.name}`));
}
} catch (error) {
console.error('Error registering application (/) commands:', error);
}
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('interactionCreate', async (interaction) => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
};
A sample module with a slash command
const { SlashCommandBuilder } = require('discord.js');
console.log('Loading ping command...');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction) {
console.log('Executing ping command...');
await interaction.reply('Pong!');
},
};
config.js
const guildConfig = require('./guildConfig.js');
module.exports = {
token: '000000',
openAIApiKey: '000000',
adminGuild: guildConfig.adminGuild.id,
memberGuild: guildConfig.memberGuild.id,
guildConfig
};
The guild ids are successfully being pulled so I’m not including the guildConfig.js file as that part is at least working.
Getting a TypeError: Cannot read properties of undefined (reading ‘on’)
const Editor = ({ socketRef, roomId, onCodeChange }) => {
const editorRef = useRef(null);
useEffect(() => {
async function init() {
editorRef.current = Codemirror.fromTextArea(
document.getElementById('realtimeEditor'),
{
mode: { name: 'javascript', json: true },
theme: 'dracula',
autoCloseTags: true,
autoCloseBrackets: true,
lineNumbers: true,
}
);
editorRef.current.on('change', (instance, changes) => {
const { origin } = changes;
const code = instance.getValue();
onCodeChange(code);
if (origin !== 'setValue') {
socketRef.current.emit(ACTIONS.CODE_CHANGE, {
roomId,
code,
});
}
});
}
init();
}, []);
useEffect(() => {
if (socketRef.current) {
socketRef.current.on(ACTIONS.CODE_CHANGE, ({ code }) => {
if (code !== null) {
editorRef.current.setValue(code);
}
});
}
return () => {
socketRef.current.off(ACTIONS.CODE_CHANGE);
};
}, [socketRef.current]);
return <textarea id="realtimeEditor"></textarea>;
};
export default Editor;
I wanted to resolve this error but I have tried many things and I am not able to resolve this issue.
I have searched everywhere and even chatgpt cannot solve this issue. If anyone knows how to solve it then please let me know.
I’ve added all the libraries correctly and I don’t know why this error is popping up.
Javascript question mark operator, multiple question marks
I get that this:
return A ? B : C
means
If A is true, return B, else return C
But how do I read this one:
return A ? B ? C : D : E
Not my code; I just need to understand it.
I’ve seen this answer/solution, but just saying “Javascript is right-associative, so you ‘resolve’ the ternaries from right to left” doesn’t seem to answer the question.
Reactjs Component to pdf
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
async function getPdfDownload() {
const content = document.getElementById("contents");
if (!content) return;
const scale = 2;
const canvas = await html2canvas(content, {
scale: scale,
useCORS: true,
logging: false,
windowWidth: content.scrollWidth,
windowHeight: content.scrollHeight,
});
const imgData = canvas.toDataURL("image/png");
const pdf = new jsPDF({
unit: "px",
format: "a4",
orientation: "portrait",
});
const pageWidth = pdf.internal.pageSize.getWidth();
const pageHeight = pdf.internal.pageSize.getHeight();
const widthRatio = pageWidth / canvas.width;
const heightRatio = pageHeight / canvas.height;
const ratio = Math.min(widthRatio, heightRatio);
const canvasWidth = canvas.width * ratio;
const canvasHeight = canvas.height * ratio;
const marginX = (pageWidth - canvasWidth) / 2;
const marginY = (pageHeight - canvasHeight) / 2;
pdf.addImage(imgData, "PNG", marginX, marginY, canvasWidth, canvasHeight);
const pagesNeeded = Math.ceil(canvasHeight / pageHeight);
for (let i = 1; i < pagesNeeded; i++) {
pdf.addPage();
pdf.addImage(
imgData,
"PNG",
marginX,
marginY - pageHeight * i,
canvasWidth,
canvasHeight
);
}
pdf.save("quote.pdf");
}
Now the problem is that on that component I tried both selecting the dom getElementById and by the ref also, this code is also working fine, but when the pdf is generated all the text is just slided downward may be by 10px, and all the other styles remain the same.
Is there a way to get a list of events an object dispatches?
Is there a way to get a list of events an object dispatches in Javascript or Typescript?
For example, if I want to see all the events that the window object dispatches is there a way to do that?
The reason is I want to verify that when I add an event listener the object has the event that I want to listen for.
I vaguely remember a method on a EventDispatch class I read somewhere that had something like, EventDispatcher.hasEvent("nameofevent"). That would help find typos and misspellings but probably not list all the events that are dispatched. But also, I believe web dev tools have a way to show all the events an object dispatches or that have event listeners added. If that is using some sort of reflection then maybe I can use that method as well. If not I’m guessing it’s using a lookup table.
Typescript React Native Image Picker double-tap issue (non expo)
So, there’s some good news and some bad news.
The good news is that the code below works.
The bad news is that I have to pick the image twice before it displays client-side.
Import code: import {launchImageLibrary} from 'react-native-image-picker'
Setting states:
const [loading1, setLoading1] = useState(false)
const [ image, setImage ] = useState('')
const [post, setPost] = useState([
{
title: '',
image: '',
user
}
])
ImagePicker code:
const uploadImage = async ( index: number )=>{
setLoading1(true)
const result = await launchImageLibrary({
mediaType: 'mixed',
quality: 1
}).then(res =>{
if(!res.didCancel){
let data = res.uri || res.assets?.[0]?.uri
setImage(data)
}
})
if(image){
setPost(prevPost =>{
const updatedPost = [...prevPost]
updatedPost[index] = {
...updatedPost[index],
image: image
}
return updatedPost
})
}
console.log('RESULT=====> ', image)
setLoading1(false)
}
The prevPost code is only for adding the image to other elements in a form post. I suspect there’s something that I’m missing in the code above that causes me to have to touch the Touchable Opacity below, pick the image from the phone, post it…..TWICE.
It works the second time I do it but not the first. Obviously, what I want is to only have to touch the Touchable Opacity, pick the image, then display it the first time I run through the process. I got no idea what I’m missing here. Any advice is welcome.
Anyway, here’s the return code:
{
post.map(( item, index )=>(
<View key={index}>
<TouchableOpacity onPress={()=>uploadImage(index)}>
<AntDesign name="link" size={20} color="black" />
</TouchableOpacity>
{
item.image && (
<Image style={styles.nft_image} resizeMode='contain' source={{ uri: item.image }} />
)
}
</View>
))
}
change string to object
how to change string to object
{‘username’: [ErrorDetail(string=’A user with that username already exists.’, code=’unique’)], ’email’: [ErrorDetail(string=’user with this email already exists.’, code=’unique’)]}
const er= {‘username’: [ErrorDetail(string=’A user with that username already exists.’, code=’unique’)], ’email’: [ErrorDetail(string=’user with this email already exists.’, code=’unique’)]}
const errorObject = JSON.parse(er);
console.log(errorObject);
