Next Js Form Values Disappear

I have a form that takes data as well as images. Everything works fine till you leave the tab and come back or on mobile, when you try uploading images it opens a folder on full screen where you can choose. Once back to the form it is empty. I wonder why it does that. Even navigating to another tab and coming back clears the whole form

Form.js

import React, { useState } from "react";
import styled from "styled-components";
import DragAndDrop from "./DragAndDrop";

function Form({ category }) {
  const [Name, setName] = useState("");
  const [Title, setTitle] = useState("");

  return (
    <>
      <div>
        <StyledForm onSubmit={SendPost}>
          <div className="mb-14">
            <H2>PRODUCT</H2>
            <StyledP type="Name : ">
              <StyledInput
                value={Name}
                placeholder="TYPE Name product name"
                onChange={(e) => setName(e.target.value)}
              />
            </StyledP>
            <StyledP type="Title : ">
              <StyledInput
                value={Title}
                placeholder="Type the Title"
                onChange={(e) => setTitle(e.target.value)}
                required
              />
            </StyledP>
            
            <StyledP type="Import photos (10 Photos Max) : " />
            <div className="mt-2">
              <DragAndDrop />
            </div>
          </div>
          <div className="-mt-8 flex justify-center">
            <button type="submit">Post</button>
          </div>
        </StyledForm>
      </div>
    </>
  );
}

const H2 = styled.h2`
`;
const StyledInput = styled.input`
`;
const StyledP = styled.p`
`;
const StyledForm = styled.form`
`;
export default Form;

Bot asking multiple times

I have my bot whenever someone says hi he replies with, “Welcome to the server!!” but he seems replying to my message multiple times, and do not get confused, it is not replying to its own message it is replying to MY message, here is the code.

client.on("messageCreate", (message) => {
 if (message.content == "hi"){
     message.reply("Welcome to the server!!")
 }

})

can i get the same result without jquery? i want to use without jquery [duplicate]

i have a javascript code that uses jquery. can i get the same result without using jquery? i want to use without jquery

can you help me?, thank you

$('.ntry').each(function() {
    var promo = $(this).find("#readingtime").attr("minutes");
    $(this).find("#rdTime").text('waktu baca ' + promo + ' menit');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<article class="ntry">
  <div class="pThmb">
    <div class="iFxd">
      <bdi id="rdTime"/> <!-- waktu baca 100 menit -->
    </div>
  </div>
  <div class="pCntn">
    <em id="readingtime" minutes="100"></em>
  </div>
</article>
<article class="ntry">
  <div class="pThmb">
    <div class="iFxd">
      <bdi id="rdTime"/> <!-- waktu baca 250 menit -->
    </div>
  </div>
  <div class="pCntn">
    <em id="readingtime" minutes="250"></em>
  </div>
</article>
<article class="ntry">
  <div class="pThmb">
    <div class="iFxd">
      <bdi id="rdTime"/> <!-- waktu baca 50 menit -->
    </div>
  </div>
  <div class="pCntn">
    <em id="readingtime" minutes="50"></em>
  </div>
</article>

Can’t compile an optional Node.js dependency with Angular compiler

I’ve created an npm library containing code that looks like this:

let _Buffer: typeof Buffer;
let _require: NodeRequire;
let _readFile: (path: string, callback: (err: (NodeJS.ErrnoException | null), data: Buffer) => void) => void;

try {
  _Buffer = typeof Buffer !== undefined && Buffer;
  _require = typeof require !== undefined && require;

  if (_Buffer && _require)
    _readFile = _require('fs').readFile;
}
catch {}

I’ve managed to make parts of the above code work in other projects, like the optional dependency on Buffer. The use of require wasn’t something I’d tried before, and this is what’s now causing me grief. Angular is determined to try to resolve the dependency on fs, no matter how I try to hide it (including silly things like _require('f' + 's')), causing an error like this:

./node_modules/@tubular/astronomy/dist/fesm2015/index.js:3:300-4:1 – Error: Module not found: Error: Can’t resolve ‘fs’ in ‘/Users/kshetline/programming_projects/svc-ng/node_modules/@tubular/astronomy/dist/fesm2015’

What I’d most like to do is figure out a way to design the npm library so this isn’t an issue at all.

A less satisfactory solution would be to find a way to tell the Angular compiler to ignore this particular external dependency. That’s a difficult subject to google, however, because searches all come up with information regarding the Angular dependency injection system, not about this type of compile-time dependency.

The goal is to allow the library to have extra Node.js features when used in a Node.js environment, but still run smoothly in a browser when those features are not available.

Save the Promise.all into two variables

I have this code and I want save the result of Promise.all into two variables.
The problem is that I gets undefined when (this.data = data)

    const {data,recents} : any = await Promise.all([
      this.$store.dispatch('algo', input),
      this.$store.dispatch('algo', input)
    ])
    this.data = data
    this.recents = recents

Blockhash not found when sending transaction

When sending a transaction using Solana web3, it sometimes shows this error:
Error: failed to send transaction: Transaction simulation failed: Blockhash not found

What is the proper way of dealing with this error other than retrying for x amount of times?
Is there a way to guarantee this issue won’t happen when sending transactions?

Animate text with array

I’m trying to animate text with javascript using an array with time intervals e.g. t te tex text, I want it to cycle from 0 to 21 and back and I’m not entirely sure how to do it. Any help is muchly appreciated!

Why does “info()” not work even though the “read” field changes?

I have a factory function, where I am returning a Book Object. When I create an object of the Book and change a field value, this is not reflected in the method of the Object. Any idea why this may be happening?

const Book = (title, author, pages, read) => {
    const info = () => {
        if (read == true) {
            return `${title} by ${author} - ${pages} pages - already read`;
        } else {
            return `${title} by ${author} - ${pages} pages - not read yet`;
        }
    }
    return { title, author, pages, read, info }; 
}

I create a Book Object using let book = Book(title, author, pages, read);
And change the value of read by accessing the read field directly.
However, when I change the value of read, this is not reflected in the info method.

ShieldUI Grid Resizing

I’m currently evaluating the demo version of ShieldUI and have been playing with the grid control. I’ve bound to a local datasource and am trying to get column resizing working properly, but when I attempt to resize individual columns, there is a large jump as the column I am resizing is resized much larger and all the other columns are sized smaller. I’m guessing I have a CSS issue as the example on the ShieldUI site only changes the size between two adjacent columns, but can’t figure out what I need to change in my style rules to get the same behavior as the example. Here’s the code I’m using, with no additional styles defined other than linking to the full minimized ShieldUI CSS:

$("#grid1").shieldGrid({
    dataSource: {
        data: HRDataset
    },
    paging: {
        pageSize: 10
    },
    sorting: {
        multiple: false,
        allowUnsort: false
    },
    columns: [
        { field: "Employee_Name", title: "Employee Name", width: 30 },
        { field: "EmpID", title: "ID", width: 10 },
        { field: "Salary", title: "Salary", width: 20 },
        { field: "Position", title: "Position", width: 30 },
        { field: "State", title: "State", width: 10 },
        { field: "Zip", title: "Zip", width: 15 },
        { field: "Sex", title: "Sex", width: 10 },
        { field: "MaritalDesc", title: "Married", width: 10 }
    ],
    scrolling: true,
    resizing: true
});

What is the proper way to calculate price given checkboxes and quantity within React?

Customers are selecting restaurant items that have options like toppings. I’m using checkboxes to allow the customer to select what options, with each checkbox having the added price of the option inside of the HTML value attribute.

There is also a quantity component that uses a callback to modify a React state.

(example of checkboxes, and quantity selection)

The code I’ve come up with to handle all of this is as follows:

    const [basePrice, setBasePrice] = useState(0);
    const [price, setPrice] = useState(0);

    useEffect(() => {
        let insert = parseFloat(props.item.price);
        setBasePrice(insert.toFixed(2));
        setPrice(insert.toFixed(2));
        setQuant(1);
    }, [props.item])

    useEffect(() => {
        calcPrice();
    }, [quant])

    const calcPrice = () => {
        let checked = document.querySelectorAll('input:checked');
        let insert = parseFloat(basePrice);

        for (let i of checked) {
            insert += parseFloat(i.value);
        }

        insert *= parseFloat(quant);

        setPrice(insert.toFixed(2));
    }

calcPrice() is also called within the onchange attribute of the div containing all of the checkboxes. Anytime a customer clicks on a checkbox, it calls calcPrice().

the first useEffect() just resets the display price (setPrice(insert.toFixed(2)) and runs every time the user selects a different item.

The problem I’m having is that whenever the customer selects an option, increases the quantity, and then switches to a new item, it doesn’t display the right price. It calls the second useEffect() before let checked = document.querySelectorAll() has a chance to run, and uses the boxes checked from the last item.

price has the $3 from last item

I have spent a full week and a half trying to combine the quantity and checkboxes properly, and–knowing that I am more than likely too stupid to see the obvious solution–am asking for help on this.

Create kind of carousel Vue

So, I have a dashboard where I want to display some cards. There should only be four visible at a time and when clicking on the arrow you just want to move one step to the next card. So let’s say cards 1-4 are showing and when clicking the right arrow you should be able to see 2-5. Right now I only have that when you click the right arrow you jump pass 1-4 and go straight to 5-10.

So right now I have this:

computed: {
    cardsToDisplay(): Status[] {
        return this.cards.slice(this.page * 4, (this.page + 1) * 4)
    },
},
methods: {
    setCards(no: number) {
        this.page = this.page + delta
    },
},

And in the template the left and right arrow buttons look like this:

        <v-icon v-if="page !==" class="black--text font-weight-bold" 
          @click="setPage(-1)">
          chevron_left</v-icon>

        <v-icon
            v-if="columns.length > (page + 1) * 4"
            class="black--text font-weight-bold"
            @click="setPage(1)"
            >chevron_right</v-icon
        >

But how can I make it just move to the next card? 🙂

DrafJS editorState html conversion is different than what the editor window displays

I’m making a rich text editor widget for netlifyCMS. I’ve already tried react-draftjs-wysiwyg but netlifyCMS doesn’t seem to be able to handle styling through classNames. So I figured I would try my hand at figuring out draftjs.

On the left is my draftJS rich text editor. And at the very top right is the draftjs-to-html conversion. As you can see, the first line is bold, so that works fine. So at least I know that I am handling state somewhat correctly.

When I change font size, the editor seems to be able to preview that properly. But when I take the editorState and convert it to html it loses the fontSize. When I log the editorState converted html it just comes out as a normal p tag with no fontSize styling.

enter image description here

Here is my custom netlifyCMS widget

import React, { Component } from "react"
import MarkdownContent from "../page-blocks/MarkdownContent"

import {Editor, EditorState,convertToRaw, RichUtils} from 'draft-js';
import draftToHtml from 'draftjs-to-html';
import 'draft-js/dist/Draft.css'
import createStyles from 'draft-js-custom-styles'

export class RichTextEditorControl extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editorState: EditorState.createEmpty(),
      isShowingFontSizeMenu: false,
    };
    // this.onChange = editorState => this.setState({editorState});
    this.handleKeyCommand = this.handleKeyCommand.bind(this);
}

onEditorStateChange = (editorState) => {
    this.setState({editorState});
    this.props.onChange(editorState)
};

// allows user to ctrl+b, ctrl+i, etc...
handleKeyCommand(command, editorState) {
    const newState = RichUtils.handleKeyCommand(editorState, command);

    if (newState) {
    this.onEditorStateChange(newState);
    return 'handled';
    }

    return 'not-handled';
}
_onBoldClick (e) {
  e.preventDefault()
  this.onEditorStateChange(RichUtils.toggleInlineStyle(
          this.state.editorState, 'BOLD'))

}
_onItalicClick (e) {
  e.preventDefault()
  this.onEditorStateChange(RichUtils.toggleInlineStyle(
          this.state.editorState, 'ITALIC'))
}
_onFontDropDownClick (e) {
  e.preventDefault();
  this.state.isShowingFontSizeMenu = !this.state.isShowingFontSizeMenu
  this.onEditorStateChange(this.state.editorState) //force re render to display drop down
}
_setFontSize(e, value, styles) {
  e.preventDefault()
  //remove current font size at selection
  const newEditorState = styles.fontSize.remove(this.state.editorState)
  //toggle dropdown
  this.state.isShowingFontSizeMenu = !this.state.isShowingFontSizeMenu
  //set editorState to display new font size
  this.onEditorStateChange(styles.fontSize.add(newEditorState, value))
}

render() {
  const {styles, customStyleFn} = createStyles(['font-size'])
  //map array of integers to display options for dropdown
  const fontSizes = [8, 10, 12, 14, 16, 18, 20, 24, 28, 32, 38, 46, 54, 62, 72]
  const fontSizeOptions = fontSizes.map(fontSize => (
          <div
              key={`font-size-${fontSize}`}
              onMouseDown={e => this._setFontSize(e, `${fontSize}px`, styles)}
          >{fontSize}</div>
      ))
    return (
        <div style={{marginTop:"20px"}}>
          {/* toolbar */}
          <div>
            <button onMouseDown={this._onBoldClick.bind(this)}>B</button>
            <button onMouseDown={this._onItalicClick.bind(this)}>I</button>
            <button
                onMouseDown={this._onFontDropDownClick.bind(this)}
            >
              Font Size
            </button>
                {/* open or close menu if the button is pressed. */}
                {this.state.isShowingFontSizeMenu ?
                    <div>
                        {fontSizeOptions}
                    </div> : null
                }

          </div>
          <div style={{border:"1px solid black", borderRadius:"2px", padding:"5px", marginTop:"20px"}}>
            <Editor
                editorState={this.state.editorState}
                handleKeyCommand={this.handleKeyCommand}
                onChange={this.onEditorStateChange}
                customStyleFn={customStyleFn}
            />
          </div>
        </div>
    );
}
}

export const RichTextEditorPreview = ({ value }) => {
  console.log(draftToHtml(convertToRaw(value.getCurrentContent())))
  return <MarkdownContent content={draftToHtml(convertToRaw(value.getCurrentContent()))} />
}

How to implement section wipe from ScrollMagic into horizontal website?

So far I built a horizontal scrolling page in html and css in reference to this article (https://redstapler.co/pure-css-horizontal-scrolling-website-tutorial/). Now I want to include wiping between two sections on the first slide using Scroll Magic (https://scrollmagic.io/). Unfotunatly I’m not being able to connect both code snippts together. Can somebody help me with this? I basically want the section .panel.first to be slided onto .slide.one while scrolling to then go forward to the next slide.

$(function () { // wait for document ready
    // init
    var controller = new ScrollMagic.Controller({vertical: false});

    // define movement of panels
    var wipeAnimation = new TimelineMax()
        .fromTo("section.panel.first", 1, {y: "-100%"}, {y: "0%", ease: Linear.easeNone}); // in from top

    // create scene to pin and link animation
    new ScrollMagic.Scene({
            triggerElement: ".slide.one",
            triggerHook: "onLeave",
            duration: "100%"
        })
        .setPin(".slide.one")
        .setTween(wipeAnimation)
        .addIndicators() // add indicators (requires plugin)
        .addTo(controller);
});
body {
  margin: 0;
  padding: 0;
}

/* horizontales scrollen */
.slide {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

.wrapper {
  display: flex;
  flex-direction: row;
  width: 400vw;
  transform: rotate(90deg) translateY(-100vh);
  transform-origin: top left;
}

.outer-wrapper {
  width: 100vh;
  height: 100vw;
  transform: rotate(-90deg) translateX(-100vh);
  transform-origin: top left;
  overflow-y: scroll;
  overflow-x: hidden;
  position: absolute;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

::-webkit-scrollbar {
  display:none;
}

/* Seite 1 - Startseite */
.one {
  background-color: #FFB111;
  width: 100vw;
}

.panel {
    height: 100%;
    width: 100%;
    position: absolute;
}

.panel.first {
    background-color: black;
}
/* Seite 2 */
.two {
  background-color: #FD5145;
  width: 100vw;
}

/* Seite 3 */
.three {
  background-color: #87B6A7;
  width: 100vw;
}

/* Seite 4 */
.four {
  background-color: #305252;
  width: 100vw;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title></title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.1.3/TweenMax.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/ScrollMagic.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/plugins/animation.gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/plugins/debug.addIndicators.min.js"></script>
  </head>
  <body>
    <div class="outer-wrapper">
      <div class="wrapper">
        <div class="slide one">
          <section class="panel first">

          </section>
        </div>
        <div class="slide two"></div>
        <div class="slide three"></div>
        <div class="slide four"></div>
      </div>
    </div>
  </body>
</html>

Display text when timer reaches 0s, and add 0 before 1-9s

I want to display some text once the timer goes to 0:00, and when the timer is anywhere in between 1-9s, I want to display a 0 in front of the seconds, e.g. 1:04 instead of 1: 4. How would I do this?

const timeSpan = document.getElementById('timer');
var sec = 600 / 60;
const mins = sec;
const now = new Date().getTime();
const deadline = mins * 60 * 1000 + now;


setInterval(() => {
  var currentTime = new Date().getTime();
  var distance = deadline - currentTime;
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);


  timeSpan.innerHTML = minutes + ':' + seconds;
  
}, 500)

How to use quills setSelection?

I am writing a custom module for quilljs. It is a simple text macro replacement tool.

ie type “.hi”, it will replace it with “hello”.

I have everything working, but the last step is meant to reposition the cursor at the end of the inserted text, but it leaves the cursor in the original location.

the problem is with line #31 quill.setSelection(…), here is the Quill setSelection API docs

// Implement and register module
Quill.register('modules/quicktext', function(quill, options) {
  
  let cache = '';
 
  quill.on('text-change', (delta, oldDelta, source) => {
    if (source === 'api') {
      console.log("changing", source) 
     return
    }
    let lastkey = delta.ops[delta.ops.length - 1]?.insert || '';
    if (delta.ops[delta.ops.length - 1]?.delete) { // handle delete key
      cache = cache.slice(0,-1);
      return
    }
    if (lastkey && lastkey !== " ") {
      cache += lastkey;
      console.log("cache", cache, "lastkey",lastkey)
    } else if (cache) { // avoid initial call
      console.log("cache", cache, "lastkey",lastkey)
      reps.forEach(rep => {
        console.log("rep check", cache, rep[cache])
        if (rep[cache]) {
          console.log("triggered")
          let caret = quill.getSelection().index
          let start = caret - cache.length - 1;
          console.log("doing", caret + (rep[cache].length - cache.length))
          quill.deleteText(start, cache.length, 'silent');
          quill.insertText(start, rep[cache], 'silent');
          console.log(`caret at ${caret}, moving forward ${rep[cache].length - cache.length} spaces, to position ${caret+rep[cache].length - cache.length}.`)
          quill.setSelection(caret + (rep[cache].length - cache.length),0, 'silent');
          // why does above not work?
          console.log("done")
        }
      })
      cache = '';
    }
  });
});

let reps = [
  {".hi": "hello"},
  {".bye": "goodbye"},
  {".brb": "be right back"}
];

// We can now initialize Quill with something like this:
var quill = new Quill('#editor', {
  modules: {
    quicktext: {
      reps: reps 
    }
  }
});

Code can be run here: Codepen