i need use react-bootstrap in the nextJs , but when need make a validation do form with checkValidaty() , the nextJS return an error - frontend

enter image description here
my code :
if(form.checkValidaty() === false ) {
event.preventDefault();
event.stopPropagation();
} else if (form.checkValidaty()) { ....
but return an error.

Related

How do I set up dynamic imports correctly (for beyond localhost)?

I followed https://docs.meteor.com/packages/dynamic-import.html to set up dynamic imports, and it works fine on localhost.
For context, I am creating a blog (Meteor/React/Apollo) which renders MDX files, and these files need to be imported, so I have a list of all my posts as such:
import("./imports/posts/61a000d03a1931b8819dc17e.mdx")
import("./imports/posts/619cae2f03f4ff710aa3d980.mdx")
import("./imports/posts/619e002d386ebf2023ea85c3.mdx")
import("./imports/posts/619fff7c5b312d7622acda86.mdx")
I have a Post.jsx component:
import React, { useState, useRef } from "react"
import { useHistory, useParams } from "react-router-dom"
import { useQuery } from "#apollo/client"
import { GET_POST_ID } from "../../api/posts/queries"
const Post = () => {
const Post = useRef()
const history = useHistory()
const { slug } = useParams()
const [loadedPost, setLoaded] = useState(false)
const [viewer, showViewer] = useState(false)
const open = () => showViewer(true)
const { data, loading, error } = useQuery(GET_POST_ID, { variables: { slug }})
if (loading) return null
if (error) {
console.log(error)
return null
}
import(`./posts/${data._id}.mdx`).then(MDX => {
Post.current = MDX.default
setLoaded(true)
}, (err) => {
console.log(err)
})
return loadedPost ? (
<>
<div className="postContent">
<div className="markdownOverride markdown-body">
<Post.current />
</div>
</div>
</>
) : null
}
export default Post
This works well and good on my local network. However, if I attempt to access it from outside my local network, an error is thrown in the console that all the blog modules are not found. The Apollo/GraphQL portion works fine, but the actual module can't be imported.
How do I get this to work outside of localhost?
Thanks.
EDIT: The error messages are, for each post:
Uncaught (in promise) Error: Cannot find module '/imports/posts/61a000d03a1931b8819dc17e.mdx`
And when I load the actual post page:
Uncaught (in promise) TypeError: Failed to fetch
Isn't your error thrown by console.log(err) ?
import(`./posts/${data._id}.mdx`).then(MDX => {
Post.current = MDX.default
setLoaded(true)
}, (err) => {
console.log(err) // <---- here
})
This means your path isn't right for /imports/posts/61a000d03a1931b8819dc17e.mdx.
To me you can't use changing parameters when doing dynamic imports.
./posts/${data._id}.mdx, because your meteor or webpack compilation needs to treat all the data._ids avalaible in your database in order to compile and prepare the file...
This might be why it works in development mode but not in production.
You can just do dynamic imports of modules or components (already compiled), no more to me. Take a look at your output compilation bundles, and try to find where are your components...
It turns out that I needed to specify the ROOT_URL correctly when initializing Meteor. With an ngrok http tunnel on port 3000 pointing to https://some-hash.ngrok.io, I had to start Meteor with: ROOT_URL="https://some-hash.ngrok.io" meteor. When I do this, I can access it fine and everything loads from my local IP and the ngrok URL, but I can't seem to load it up from localhost (it times out).
Specifying my local or public IP did not work, I could not get it to load through any of those methods.

Renderer process out of memory after app is packaged into EXE

Expected Behavior
In my main renderer window I'm initializing UI from an imported module. When running the app in dev mode everything works but once I package the app into EXE and try to run it, I'm getting renderer process out of memory error.
The expected behavior is that the packaged app should run like the dev mode.
Actual Behavior
I've checked the electron logs and memory consumption in windows task manager. The memory usage keeps increasing until the renderer process crashes and electron logs oom error.
Since I'm new to electron I've read the documentation but unable to figure out why the same thing is running perfectly in dev mode and crashes in prod.
Log : Renderer process oom - see https://www.electronjs.org/docs/tutorial/application-debugging for potential debugging information.
Another log after some time : [19156:0921/120104.184:ERROR:gpu_init.cc(440)] Passthrough is not supported, GL is swiftshader
So this is what I'm trying to do -
Import my module which is served on localhost:
This module exposes an object - Tesseract through which I initialize my UI.
In the component which is rendered in my main browser window I initialize the UI like this:
File - index.tsx
useEffect(() => {
if (tsToken) {
Tesseract.ui
.init(tsToken.tsToken, "random_id")
.then((sdk: any) => {
console.log("🚀 ~ file: index.js ~ line 3 ~ sdk", sdk);
// After this line nothing is logged and renderer process crashes (But works when I run electron in dev mode)
sdk.init({
...MasterConfig,
RootElement: document.getElementById("tesseract-root"),
});
const authToken = sessionStorage.getItem("ts_token");
ipcRenderer.send("set-globals", { TAC: authToken });
})
.catch((err: any) => console.error(err));
}
}, [tsToken]);
return <></>;
In the above piece of code we pass a root element to the init method. The init method then initializes a react app in that root element.
EDIT:
This is the init method in that module
SDK.prototype.init = async function (config) {
try {
const parsedConfig = JSON.parse(this.META.uiConfig);
window.Tesseract.ui["MasterConfig"] = merge(parsedConfig, config);
window.Tesseract.ui["info"] = this.META;
const projectType = window.Tesseract.ui.MasterConfig.ProjectConfig.type;
console.log("🚀 ~ file: lib.js ~ line 51 ~ projectType", projectType)
const MasterConfig = window.Tesseract.ui["MasterConfig"];
console.log(MasterConfig);
if (
MasterConfig &&
MasterConfig.UserProperties &&
MasterConfig.UserProperties.userId
) {
console.log("React init here");
// Console logs upto this point and then everything fails
// No error logged
try {
RecorderUI.ReactApp({ ...parsedConfig, ...config }).then((obj) => {
// This is never logged
console.log("UI rendered");
return obj;
}).catch(err => console.log(err));
} catch (err) {
console.log(err);
return err;
}
} else {
const e = new Error("User Id Missing");
e.name = "Missing unique user Id";
throw e;
}
} catch (err) {
console.error(err);
return err;
}
};
This is the UI rendering method:
export default async function entry(config) {
// This is never logged so basically something is happening before this
console.log("somemmthing something");
console.log("Root Element: ",
window.Tesseract?.ui?.MasterConfig?.RootElement);
try {
const { RootElement } = config;
RootElement.attachShadow({ mode: "open" });
await IDBStore.create({
version: 1,
name: "ext",
schema: {
globals: "&key",
},
});
const shadowRoot = RootElement.shadowRoot;
const styleElement = document.createElement("style");
styleElement.innerHTML = `${LoaderCss} ${SourcePreviewCSS} ${NotificationCss} ${LibraryCss} ${SelectModeCss} ${WebcamBoxCss} ${CameraBubbleCss} ${countdownCss} ${indexStyles} ${commonCss} ${colorsCss} ${homeCss} ${recordCss} ${advancedOptionsCss} ${recordingTypesCss} ${toggleOptionsCss} ${tourOverlayCss} ${headerCss} ${checkboxCss} ${tooltipCss} ${dropdownCss} ${toggleCss} ${recordButtonCss} ${bannersCss} ${toolsCss} ${canvasCss} ${paintCss} ${recordingControlsCss} ${controlsMainCss}`;
const reactRoot = document.createElement("div");
reactRoot.setAttribute("id", "react-root");
shadowRoot.appendChild(styleElement);
shadowRoot.appendChild(reactRoot);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
reactRoot
);
window.addEventListener("message", handleMessaging, false);
} catch (err) {
console.error(err);
return new Error(err);
}
}
I've read numerous blog posts, github issues but unable to find what's causing this. I need help in determining what is the difference in internal workings of electron which causes such difference b/w running in dev mode vs. packaging the app.

Discord.JS ReferenceError: stopTyping is not Defined

I'm trying to get our announce command to work but it keeps throwing the following error:
#Nimbi, An error occurred while running the command: ReferenceError: stopTyping is not defined
You shouldn't ever receive an error like this.
Please contact Nimbi#4961.
Here is my announce.js code:
const stripIndents = require('common-tags').stripIndents;
const { Command } = require('discord.js-commando');
require('dotenv').config();
ANNOUNCE_CHANNEL_NAME = process.env.ANNOUNCEMENT_CHANNEL;
NEWS_CHANNEL_NAME = process.env.NEWS_CHANNEL;
MODLOG_CHANNEL_NAME = process.env.MODLOG_CHANNEL;
module.exports = class NewsCommand extends Command {
constructor (client) {
super(client, {
name: 'announce',
memberName: 'announce',
group: 'mod',
aliases: ['news', 'ann', 'a'],
description: 'Make an announcement in the news channel',
format: 'Announcement',
examples: ['announce John Appleseed reads the news'],
guildOnly: true,
throttling: {
usages: 2,
duration: 3
},
args: [
{
key: 'body',
prompt: 'What do you want me to announce?',
type: 'string'
}
],
userPermissions: ['MANAGE_MESSAGES'],
clientPermissions: ['MANAGE_MESSAGES']
});
}
run (msg, {body}) {
try {
startTyping(msg);
let announce = body,
newsChannel = null;
const announceEmbed = new MessageEmbed(),
modlogChannel = msg.guild.settings.get('modLogChannel',
msg.guild.channels.find(c => c.name === MODLOG_CHANNEL) ? msg.guild.channels.find(c => c.name === MODLOG_CHANNEL).id : null);
if (msg.guild.settings.get('announcechannel')) {
newsChannel = msg.guild.channels.find(c => c.id === msg.guild.settings.get('announcechannel'));
} else {
msg.guild.channels.find(c => c.name === 'announcements')
? newsChannel = msg.guild.channels.find(c => c.name === ANNOUNCEMENT_CHANNEL)
: newsChannel = msg.guild.channels.find(c => c.name === NEWS_CHANNEL);
}
if (!newsChannel) throw new Error('nochannel');
if (!newsChannel.permissionsFor(msg.guild.me).has(['SEND_MESSAGES', 'VIEW_CHANNEL'])) throw new Error('noperms');
newsChannel.startTyping(1);
announce.slice(0, 4) !== 'http' ? announce = `${body.slice(0, 1).toUpperCase()}${body.slice(1)}` : null;
msg.attachments.first() && msg.attachments.first().url ? announce += `\n${msg.attachments.first().url}` : null;
announceEmbed
.setColor('#AAEFE6')
.setAuthor(msg.author.tag, msg.author.displayAvatarURL())
.setDescription(stripIndents`**Action:** Made an announcement`)
.setTimestamp();
newsChannel.msg.say(announce);
newsChannel.stopTyping(true);
if (msg.guild.settings.get('mod-logs', true)) {
if (!msg.guild.settings.get('hasSentModLogMessage', false)) {
msg.reply(oneLine`📃 I can keep a log of moderator actions if you create a channel named **${MODLOG_CHANNEL_NAME}**
(or some other name configured by the ${msg.guild.commandPrefix}setmodlogs command) and give me access to it.
This message will only show up this one time and never again after this so if you desire to set up mod logs make sure to do so now.`);
msg.guild.settings.set('hasSentModLogMessage', true);
}
modlogChannel && msg.guild.settings.get('mod-logs', false) ? msg.guild.channels.get(modlogChannel).msg.say('', {embed: announceEmbed}) : null;
}
stopTyping(msg);
return msg.embed(announceEmbed);
} catch (err) {
stopTyping(msg);
if ((/(?:nochannel)/i).test(err.toString())) {
return msg.reply(`there is no channel for me to make the announcement in. Create channel named either ${ANNOUNCE_CHANNEL_NAME} or ${NEWS_CHANNEL_NAME}`);
} else if ((/(?:noperms)/i).test(err.toString())) {
return msg.reply(`I do not have permission to send messages to the ${ANNOUNCE_CHANNEL_NAME} or ${NEWS_CHANNEL_NAME} channel. Better go fix that!`);
}
return msg.reply(oneLine`An error occurred but I notified ${this.client.owners[0].username}
Want to know more about the error? Join the support server by getting an invite by using the \`${msg.guild.commandPrefix}invite\` command `);
}
}
};
My discord.js version is: ^12.5.1
My discord.js-commando version is: ^0.11.1
My node.js version is: ^12.0.0
I've already tried defining it with:
const {startTyping, stopTypeing } = require('discord.js');
and
const {startTyping, stopTypeing } = require('util');
however, both simply threw the startTyping is not a function error.
Any help would be much appreciated.
Note: this is in discord.js#13 and onwards
startTyping
// like 101arrowz said, startTyping (or now sendTyping) is a method of the TextChannel, which you can get by msg.channel
message.channel.sendTyping()
Discord.js and commando (which is by the same people) works great, but if you have any problems I suggest you read the docs or ask at their discord server (they do actually help)

Module not found: Error: Can't resolve '../../../vue-temp/vue-editor-bridge' in 'D:\laravel projects\codeGram\resources\js\components'

i am using laravel + vuejs to do the follow and unfollow button of instagram clone , but i get this error i did everything i could, checked the config.js , deleted the module package and again run the npm install but it didnt work here is my code
<template>
<div>
<button class="btn btn-primary ml-4" #click="followUser" v-text="buttonText">Folloq</button>
</div>
</template>
<script>
import func from '../../../vue-temp/vue-editor-bridge';
export default {
props: ['userId', 'follows'],
watch: {
status: function() {
this.buttonText = (this.status) ? 'Unfollow' : 'Follow';
}
},
data: function () {
return {
status: this.follows,
buttonText: this.follows ? 'Unfollow' : 'Follow'
}
},
methods: {
followUser() {
axios.post('/follow/' + this.userId)
.then(response => {
this.status = ! this.status;
console.log(response.data);
})
.catch(errors => {
if (errors.response.status == 401){
window.location = '/login';
}
});
}
},
}
</script>
my code in the view in index.blade.php for the button is
<follow-button user-id="{{$user->id}}" follows="{{ $follows }}"></follow-button>
route is
Route::post('follow/{user}','App\Http\Controllers\FollowsController#store');
full error
ERROR in ./resources/js/components/FollowButton.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib/index.js??clonedRuleSet-5[0].rules[0].use[0]!./node_modules/vue-loader/lib/index.js??vue-loader-options!./resources/js/components/FollowButton.vue?vue&type=script&lang=js&) 7:0-55
Module not found: Error: Can't resolve '../../../vue-temp/vue-editor-bridge' in 'D:\laravel projects\codeGram\resources\js\components'
I assume you don't want to use this at all:
import func from '../../../vue-temp/vue-editor-bridge';
Vscode imports this 'func' from a module when you want to autocomplete while writing function. This is totally annoying and if anybody knows how to turn it off, you would be my personal hero!
VS Code automatically added in your code line like:
import func from 'vue-editor-bridge'
Find it in your code and remove it. Done!
I faced this problem too, and it happens because, instead of typing complete function in the code, I used the autocomplete version of function which was func and as func is a totally different thing in Vue, as compared to function, Vue just put import func from 'vue-editor-bridge'.
Just change the word func to function and remove this import inside the script tag and it will be ok.
That's how it works for me.
If you are in vue and your error starts like this 'Module not found: Error: Can't resolve 'http' ...' installing url-loader will do the trick. Just install it using npm.
npm install --save-dev url-loader

nodejs cookie-session typeerror

TypeError: this.keys.index is not a function
the console log show that the if condition line is error
app.get('/',(req,res)=>{
if(!req.session.authenticated){
res.redirect('/login');
}else{
res.redirect('/search')
}
})
it was fine until i start another server.js from a completely different folder. I have tried to reinstall the node_module to fix it but it just result the same. but the weird part is i can start the server in a vm without any problem. can any help me with this?
Cookies.prototype.get = function(name, opts) {
var sigName = name + ".sig"
, header, match, value, remote, data, index
, signed = opts && opts.signed !== undefined ? opts.signed : !!this.keys
header = this.request.headers["cookie"]
if (!header) return
match = header.match(getPattern(name))
if (!match) return
value = match[1]
if (!opts || !signed) return value
remote = this.get(sigName)
if (!remote) return
data = name + "=" + value
if (!this.keys) throw new Error('.keys required for signed cookies');
index = this.keys.index(data, remote)
if (index < 0) {
this.set(sigName, null, {path: "/", signed: false })
} else {
index && this.set(sigName, this.keys.sign(data), { signed: false })
return value
}
};
I realise that this answer is late in the day but might help someone with the same error. I was getting the error 'TypeError: this.keys.index is not a function' on line 73 of index.js in cookies when trying to use koa-session.
I eventually realised that I had set app.keys to a single value i.e.
app.keys = 'dieueyf7huienejnfef'
When it should be an array:
app.keys = ['dieueyf7huienejnfef']

Resources