self is not defined error when i am using jodti-react text edior in nextjs project

self is not defined error when i use jodti-react in nextjs project

import React, { useState, useRef, useMemo } from "react";
import Dashborad from "./Dashborad";
import JoditEditor from "jodit-react";
import dynamic from "next/dynamic";

export default function edit() {
  const editor = useRef();
  const [content, setContent] = useState("");

  return (
    <Dashborad>
      <JoditEditor
        ref={editor}
        value={content}
        tabIndex={1} // tabIndex of textarea
        onBlur={(newContent) => setContent(newContent)} // preferred to use only this option to update the content for performance reasons
        onChange={(newContent) => setContent(newContent)}
      />
    </Dashborad>
  );
}

}

how to solve this error ?

How does this empty object gets filled with the array values?

function charcheck(str){
  var obj = {}
    for(i=0;i<str.length;i++){
        let allchar = str[i]
        if(obj[allchar] > 0){
            obj[allchar]++
        }
        else{
            obj[allchar] = 1
        }
    }
    return obj
}

expected input = charcheck(“apple”)
expected output = {a: 1, p: 2, l: 1, e: 1}

This code is working as expected BUT I have declared the obj empty at start, so when does this obj get’s stored with the str values, i don’t understand in this code

i tried to check the obj[allchar] value by console logging it but it displays the number

next-auth/discord callbacks arent modifying data

I’m using next-auth/discord however when using the session callback to set a user id to the session it does not set the property.

[...nextauth].js

import NextAuth from "next-auth/next";
import DiscordProvider from "next-auth/providers/discord";

export default NextAuth({
  providers: [
    DiscordProvider({
      ...
      session: {
        strategy: "jwt",
        ...
      },
      callbacks: {
        async session({ session, user }) {
          session.user.id = user.id;
          return session;
        }
      }
    })
  ]
});

/api/page.js

export default async function handler(req, res) {
  const session = await getSession({ req });
  console.log(session);
}

This logs:

{
  user: {
    name: ...,
    email: ...,
    image: ...
  },
  expires: ...
}

With no user.id property.

Vue 3 list does not update

We are fetching data from API like:

<script setup>
import { onMounted, inject } from 'vue'

let list = [];

function init() {
    axios
        .post("/some-link/here")
        .then((o) => {
            list = o.data.bla;
            console.log(list);
        })
        .catch((o) => {
            //TO DO 
        });
}

onMounted(() => {
    init();
});
</script>

The console.log shows the list properly.

But on the template, it does not update.

<p v-for="(val, index) in list" :key="index">
   {{ val.name }}
</p>

Deploying github repo to railway. app resulting – Application Error Is your app correctly listening on PORT?

There was a solution available on github of adding the variable i did that, what ever i put port number it says already in use, follow is the error on deploy log..

   listening on port 9586
   Port 9586 is already in use
  [nodemon] app crashed - waiting for file changes before starting...

Following is the error when i open the deployed link
Application Error

 Is your app correctly listening on $PORT?

View the deployment below to check for errors

this is the link of deployed repo https://rehub-backend.up.railway.app/ ,
Please do assist if u have any idea

How to insert a div tag in more than one location at the same time? [duplicate]

I have a div tag with class name insert. I want to move this tag to several locations onclick. Here is my code:

<!DOCTYPE html>
<html>
    <script>
    function MyInsert() {
        var toBeInserted = document.querySelector("div.insert");
        var targetTag = document.querySelectorAll("div.small-container");
        const insertArray = [];

        for (i = 0; i < targetTag.length; i++) {
          insertArray.push(toBeInserted);
        }

        for (j = 0; j < targetTag.length; j++) {
            targetTag[j].parentNode.insertBefore(insertArray[j], targetTag[j]);
        }
    }

    </script>
    <body>
    <h1>This is a test page</h1>
    <div class="main-container" onclick="MyInsert()">
        <div class="small-container">
            <h5>How are you?</h5>
        </div>
        <div class="small-container">
            <h5>How are you?</h5>
        </div>
        <div class="small-container">
            <h5>How are you?</h5>
        </div>
        <div class="small-container">
            <h5>How are you?</h5>
        </div>
    </div>
    <div class="insert">
        <h5>Insert me in each small-container div class!</h5>
    </div>
    </body>
</html>

Basically, when I click on anything within the div class main-container, I want to place the div class insert before each of the small-container classes. At present, the insert class only gets placed before the last instance of the small-container class. It doesn’t get placed in the first three instances of the small-container class.

how to minimize a div with only javascript [duplicate]

hello i really need help for a project thats due tomorrow , i want to achieve something like this http://jsfiddle.net/miqdad/Qy6Sj/1/ but with no jquery
, i also dont wanna expand it i wanna do the opposite i wanna minimize a div thats already shown . thanks in advance

I googles but nothing showed

$("#button").click(function(){
    if($(this).html() == "-"){
        $(this).html("+");
    }
    else{
        $(this).html("-");
    }
    $("#box").slideToggle();
});

Jquery Move block on mouse move

I need script which would change translateX position depends on mouse position inside of this block.
https://www.peaktwo.com/work/
Here’s how it looks on a live website, can’t achieve this effect.
Can somebody help to do that on jQuery?

$('.work__main').on("mousemove" ,function(e){
            let center = $(window).width()/2;
            if ((center - event.pageX) > 0 ) {
                $('.work__main').css("transform" , "translateX(-"+ event.pageX/10 +"px)")
            } else {
                $('.work__main').css("transform" , "translateX(-"+ event.pageX/10 +"px)")
            }
    });

Here’s my code – but when I’m trying to build it like that – when I put my mouse on a center it jumps from one side to another

How do I set the value of a search bar using loadUrl javascript:documentation.value?

I’m trying to open a webpage in a webview and search a string that is entered by the user (this is going to be a part of a later app)

MainActivity.java

package com.example.webtest;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String drug1 = "tetracycline";

        webView = (WebView) findViewById(R.id.webview);
        webView.setWebViewClient(new WebViewClient());
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("https://www.drugs.com/drug_interactions.html");

        webView.setWebViewClient(new WebViewClient(){
            @JavascriptInterface
            public void onPageFinished(WebView view, String weburl){
                webView.loadUrl("javascript:document.getElementById('livesearch-interaction-basic').value = drug1; null");
                webView.loadUrl("javascript:document.getElementsByTagName('input')[2].click()");
                webView.loadUrl("javascript:document.getElementById('livesearch-interaction').value = 'isotretinoin'; null");
                webView.loadUrl("javascript:document.getElementsByTagName('input')[2].click()");
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    public void run() {
                        webView.loadUrl("javascript:document.querySelectorAll('a[href='https://www.drugs.com/interactions-check.php']').click()");
                    }
                },3000);   //12 seconds
            }
        });
    }
}

I have tried using

webView.loadUrl("javascript:document.getElementById('livesearch-interaction-basic').value = drug1; null");

and

webView.loadUrl("javascript:document.getElementById('livesearch-interaction-basic').value = (drug1); null");

When I run the app, it enters the second value but not the first one with the variable. Does anyone know how I can fix this?

Frontend mi backend mi [closed]

Bu site yazılım öğrenme konusunda en başta bana yardımcı olur mu?

html css js üzerinde çalışıp frontend üzerine kendimi geliştirmek istiyorum. Bu konuda frontend bir yazılımcı olmak yeterli midir? Backend üzerine de çalışmam gerekir mi?

GET […] net::ERR_ABORTED 404 (NOT FOUND)

I have a question concering this error message:
I have an index.html file, script.js file and an app.py file. The app.py file is directly in the project folder while the other two files are located in a additional folder (called “template”), so app.py and template have the same “level”.

In the app.py I just return the index.html file so what I do is this:

from flask import Flask, render_template

app = Flask(__name__)


@app.route("/", methods=["GET"])
def getIndexHTML():
    return render_template("index.html")


if __name__ == "__main__":
    app.run(debug = True)

In the index.html I have this:

<!DOCTYPE html>
<html lang="de">
<head>
   <meta charset="utf-8">
   <title>test</title>
</head>
<body>
    <button id="1" onclick="testing()">Click it</button>
    <script src="script.js"></script>
</body>
</html>

And in the script.js this:

function testing() {
  document.getElementById("1").innerHTML = "Clicked!";
}

I kept it simple because the main issue is that I get the error message “GET http://127.0.0.1:5000/script.js net::ERR_ABORTED 404 (NOT FOUND)” and I have no clue why…
But I know the problem is the path in src=”…” so I tried these already:

<script src="script.js"></script>
<script src="/script.js"></script>
<script src="./script.js"></script>

I also tried the absolute path

So basically I tried every possible path I could imagine but nothing worked. I saw some related posts in stackoverflow but the none of the answers were the solution to my problem. What did I do wrong here?

mockResolvedValueOnce works with await but mockRejectedValueOnce doesn’t

I am working on my test for a new project and have them set up but am running into an async issue with jest.

I start with jest.mock('axios');

And the working test is

it('Dispatches SNACK_BAR after submitting ForgotPassword', async () => {
    let store = configureStore({ reducer: {
      auth: authReducer,
      snackBar: snackBarReducer
    }})

    axios.post.mockResolvedValueOnce({headers: {
      authorization: 'asdasdasdas'
    },
    status: 200});

    await store.dispatch(forgotPasswordActions.forgotPasswordPost('[email protected]', (path) => {}))
    expect(store.getState().snackBar).toEqual({"message": "Check your email for a reset link", "severity": "success", "timestamp": store.getState().snackBar.timestamp});
  });

But when I try the fail case

it('Dispatches SNACK_BAR after submitting ForgotPassword with an error', async () => {
    let store = configureStore({ reducer: {
      auth: authReducer,
      snackBar: snackBarReducer
    }})
    
    axios.post.mockRejectedValueOnce({response: {headers: {
        authorization: 'asdasdasdas'
      },
      status: 500,
      data: {
        error: 'Error'
    }}});

    await store.dispatch(forgotPasswordActions.forgotPasswordPost('[email protected]', (path) => {}))
    expect(store.getState().snackBar).toEqual({"message": "Error", "severity": "error"});
  })

The expect doesn’t wait for the dispatch to resolve. If I change the mockRejectedValueOnce to mockResolvedValueOnce then I get a similar result to the first test. It seems the only difference is mockRejectedValueOnce but I am not sure why

setState Updating all instances of Component React

I’m trying to create a quizlet-learn kind of app, and I have multiple instances of Card components. I have it set so when I pick an answer on one of the cards, it updates the state and display based on what I picked. There are buttons at the bottom to change the card. The issue is when I pick an answer on a card, the state is updated for every card component and showAnswer is set to true. How can I prevent this from happening and make it only update the same card?

My card component:

export default class Card extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            option_correct: Math.random() > 0.5,
            showAnswer: false,
            optionPicked: 0
        }
    }

    handleClick(optionPicked) {
        console.log(this.state.showAnswer);
        console.log(this.props.prompt + ' 1');
        if (!this.props.hidden) {
            if (!this.state.showAnswer)
                this.setState({
                    optionPicked: optionPicked
                });
            this.setState({
                showAnswer: true
            });
        }
    }

    handleKeyPress(event) {
        console.log(prompt + ' 2');
        if (event.key === 'Enter') {
            this.props.onFinish();
            event.preventDefault();
        }
    }

    render() {

        console.log(this.props.prompt + ' ' + this.state.showAnswer);

        return (
            <div className={`card ${this.state.showAnswer ? "show_answer" : ""}`} onKeyDown={this.handleKeyPress}>
                <div className='prompt'>
                    {this.props.prompt}
                </div>
                <small className={'continue'}>
                    Press Enter to Continue...
                </small>
                <div className='options'>
                    <button className={'option ' +
                        (this.state.option_correct ? 'correct' : 'wrong')
                        + ' ' + (this.state.optionPicked === 1 ? 'picked' : 'not_picked')} onClick={() => {
                        this.handleClick(1);
                    }}>
                        {this.state.option_correct ? this.props.answer : this.props.wrongAnswer}
                    </button>
                    <button className={'option ' + (this.state.option_correct ? 'wrong' : 'correct')
                        + ' ' + (this.state.optionPicked === 2 ? 'picked' : 'not_picked')} onClick={() => {
                        this.handleClick(2);
                    }}>
                        {this.state.option_correct ? this.props.wrongAnswer : this.props.answer}
                    </button>
                </div>
            </div>
        );
    }
}

My card container component:

class CardData {
    constructor(prompt, answer, wrongAnswer) {
        this.prompt = prompt;
        this.answer = answer;
        this.wrongAnswer = wrongAnswer;
    }
}

export default function Cards() {
    const [flashcarddata, setFlashcarddata] = useState([]);
    const [current, setCurrent] = useState(0);

    useEffect(() => {
        setFlashcarddata([
            new CardData('word1', 'correct', 'incorrect'),
            new CardData('word2', 'correct 2', 'incorrect 2'),
            new CardData('word3', 'correct 23', 'incorrect 23')
        ])
    }, []);

    const cards = flashcarddata.map((card, index) => {
        return <Card
            prompt={card.prompt}
            answer={card.answer}
            wrongAnswer={card.wrongAnswer}
            hidden={current !== index}
            onFinish={() => {
                console.log('finished ' + card.prompt);
                nextCard();
            }}
        />;
    });

    function previousCard() {
        setCurrent(current - 1);
    }
    function nextCard() {
        setCurrent(current + 1);
    }

    const loading = <div className="loading">Loading card...</div>;

    return (
        <div>
            {flashcarddata && flashcarddata.length > 0 ? cards[current] : loading}

            <div className="nav">
                {current > 0 ? (
                    <button onClick={previousCard}>Previous card</button>
                ) : (
                    <button className="disabled" disabled>
                        Previous card
                    </button>
                )}
                {current < flashcarddata.length - 1 ? (
                    <button onClick={nextCard}>Next card</button>
                ) : (
                    <button className="disabled" disabled>
                        Next card
                    </button>
                )}
            </div>
        </div>
    );
}

So far I’ve tried to change Card into a class from a function component, make the handleClick method only work if the card was the one being displayed, and changed from having every card being rendered and having most of them set display: block in css to having just one card rendered at a time.

NodeJs: Write export in ES6 Sytax

I am currently working on a bot, that I write with node.js

However, I have this piece of code: commands/server.js

const { SlashCommandBuilder } = require("discord.js");

module.exports = {
  data: new SlashCommandBuilder()
    .setName("server")
    .setDescription("Provides information about the server."),
  async execute(interaction) {
    // interaction.guild is the object representing the Guild in which the command was run
    await interaction.reply(
      `This server is ${interaction.guild.name} and has ${interaction.guild.memberCount} members.`
    );
  },
};

I call it inside my index.js like this:

//for every command we have
for (const file of commandFiles) {
  //get the file path
  const filePath = path.join(commandsPath, file);
  //load our command_name.js
  const command = require(filePath);
  // Set a new item in the Collection with the key as the command name and the value as the exported module
  if ("data" in command && "execute" in command) {
    client.commands.set(command.data.name, command);
  } else {
    console.log(
      `[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`
    );
  }
}

What would be the equivalent in ES6 syntax for server.js, when I set my type to module && want to use the import syntax – so I still got the data and execute property.

Edit a modal with option selected with onchange function

Im trying to open a edit modal, and load the results of this query.
My problems is the function “onchange” continue loading after the element was selected and changed it.

This is the function on the button to open the modal

const editModal = async (id, company, element) => {
 
  $("#companyEdit").val(insumo).select2().val();
  $("#elementEdit").val(element).select2().val();

  $("#edit").modal("show").attr("data-id", id);
 
};



This is the front

          .modal-body
                    .row(style="padding:15px;")
       
                        .col-md-12.col-12
                                .form-group
                                    label Company:
                                        select#companyEdit(onChange="selectElement()")
                                            option(disabled value=null) --Select-- 
                                            option(value=0) Sin asignar  
                                                each item in company
                                                    option(value=item.id)= item.name
                                     
                     
                        .col-md-12.col-12
                            .form-group
                                label Element:
                                .controls
                                    select#elementEdit(disabled)

This code works but delete the selected company.

const selectElement= async () => {


  let valueCompany= $("#companyEdit")
  let valueElement= = $('#elementEdit')
 
  const company_id= valueCompany.select2().val();
 

  $.ajax({
    method: "GET",
    url: `/admin-elements/${company_id}`,
    dataType: "json",

    success: function (data) {

      if (data.sucess == 200) {
        valueElement.empty();
        for (i = 0; i < data.result.length; i++) {
          valueElement.append('<option value="' + data.result[i].name+ '">' + data.result[i].name+ '</option>');
        }
        valueElement.attr("disabled", false);

      } else {
        valueElement.append(
          '<option value="">--</option>'
        );
        valueElement.attr("disabled", false);
      }
    },
    error: function (e) {
       ...
    },
  })

}

Thanks very much!!

I want can open a modal and see the select with the correct value with the possiblity of changed it with a query.