How do i make the data in the input feild of my form in next js stay after refresh of the page?

I am working on a form in nextjs and i would love the data to remain the same i.e persist after the entire page as been refreshed or reloaded . Local storage doesnt work with next js , so i am looking for an alternative , i always get local storage not defined when i use it
Here is my code below

import React, { useState, useEffect, useLayoutEffect, createContext , useContext } from "react";
import { useRouter } from "next/router";
import Cookie from "js-cookie";
import { parseCookies } from "../helpers/index";
import { Formik } from "formik";
function Form() {
  
  return (
    
      <div>
     
      <form action="" >
        <section class="left">
          <div class="input-container">
            <label for="name">Full name</label>
            <input
              type="text"
             
            />
          </div>
          <div class="input-container">
            <label for="age" required>
              Mobile Number
            </label>
            <input
              type="text"
              
            />
          </div>
          <div class="input-container">
            <label for="phone">Choose password</label>
            <input
              type="text"
             
            />
          </div>
          
            
          </div>
        </section>
      </form>
      
    </div>


  );
}

export default Form;


  

THANK YOU SO MUCH

Why does my javascript variable not submit with my HTML form?

I have the following line in my JS file for a variable I have already defined;

document.getElementById("total").value = total;

I then have the following line in my HTML form which I would like to be set with the total value above;

<input type="hidden" id="total" name="total"/>

However, when I submit my form I cannot see this total value being set? I am referencing this JS file in other spots so I don’t believe it’s a referencing issue. Am I setting the variable incorrectly in the form element?

The value is just blank in my $_POST data

TIA

I am trying to connect my web page to my local server database but I am getting error ECONNREFUSED

 errno: -61,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 3000,
  fatal: true

I am using Mac OS and VS Code to connect to my local server. I have connected mysql workbench to VSCode as well and it is working fine. But when I try to connect it with my program it is not working. I changed the hostname from ‘localhost’ to ‘127.0.0.1’ as well still no luck. Also, I changed my port from 3306 to 3000 as it was not connecting and I got the following error

code: 'ER_ACCESS_DENIED_ERROR',
  errno: 1045,
  sqlMessage: "Access denied for user 'usersql'@'localhost' (using password: YES)",
  sqlState: '28000',
  fatal: true

My code:

const { createPool } = require('mysql')

const pool = createPool({
    host: "127.0.0.1",
    user: "usersql",
    password: "password123",
    database: "userdb",
    connectionLimit: 10,
    port: 3000
})

pool.query(`select * from userdb.New_Customer`, function(err, result, fields) {
    if (err) {
        return console.log(err);
    }
    return console.log(result);
})

Reverse a string algorithm – JavaScript

I’m trying to solve this algorithm but am getting undefined at the beginning. Can anybody explain why this is happening so I may solve it?

// Given a String S, reverse the string without reversing its individual words. Words are separated by dots.

function reverseStr(str){
    newStr="";
    for(var i=str.length;i>=0;i--){
        newStr+=str[i];
    }
    console.log(newStr);
}

reverseStr("hcum.yrev.margorp.siht.ekil.i");

Output: undefinedi.like.this.program.very.much

gruntjs – Uncaught SyntaxError: Identifier has already been declared

I am using grunt to uglify my Js code, but when I test my code in the browser I get:

Uncaught SyntaxError: Identifier has already been declared

Here is an example of the test I di:
files:

testA.js-

export const myData = {
  a: "hello",
  b: "Me",
};

testB.js-

import { myData } from "./testA.js";

const doSomething =()=>{
    console.log(myData);
}

doSomething();

uglify file:

test.min.js-

const myData = { a: "hello", b: "Me" };
import { myData } from "./testA.js";
const doSomething = () => {
    console.log(myData);
  },
  myData = (doSomething(), { a: "hello", b: "Me" });
import { myData } from "./testA.js";
const doSomething = () => {
  console.log(myData);
};
doSomething();
export { myData, myData };

As you can see myData is exported twice but the error line starts at line 2.
Is there a way to prevent grunt from creating duplicate identifiers to fix the problem?

quicktype-core: generating TypeScript interfaces that allow extra unknown properties when parsing, without throwing an exception

I’m using NPM package: https://www.npmjs.com/package/quicktype-core to generate TypeScript interfaces from JSON samples.

Here’s a simple example of the code that generates the interfaces:

const sample_object = {
    prop_a: 'value A',
    prop_b: 'value B',
};

const jsonInput = jsonInputForTargetLanguage('typescript');
await jsonInput.addSource({
    name: 'MyNewInterface',
    samples: [JSON.stringify(sample_object)],
});
const inputData = new InputData();
inputData.addInput(jsonInput);

const result = await quicktype({
    inputData,
    lang: 'typescript',
    inferDateTimes: false,
    alphabetizeProperties: true,
    inferEnums: false,
    rendererOptions: {},
});

// Display generated interface:
const generated_code = result.lines.join('n');
console.log(generated_code);

The interface that it generates works when parsing new data that ONLY contains the properties it knows about. But if you try to parse some data that contains any extra fields/properties, it throws an exception, e.g. sample data:

const sample_object = {
    prop_a: 'value A',
    prop_b: 'value B',
    new_extra_property: 'value for new_extra_property',
};

Will throw exception:

Invalid value "value for new_extra_property" for type false

How can I configure quicktype-core to generate code that will NOT throw exceptions when data contains extra unknown fields?

I’ve tried trawling through the quicktype source code, and came across a couple of rendererOptions called additionalProperties + runtimeTypecheckIgnoreUnknownProperties … but trying to set those as either true or a string doesn’t make any difference at all to the code it generates.

Setting to true (actually gives TypeScript errors for the code, even though many quicktype-option renderedOptions are actually bools, and they’ve worked for other settings):

const result = await quicktype({
    inputData,
    lang: 'typescript',
    inferDateTimes: false,
    alphabetizeProperties: true,
    inferEnums: false,
    rendererOptions: {
        additionalProperties: true,
        runtimeTypecheckIgnoreUnknownProperties: true,
    },
});

Setting a string (keeps the TypeScript checking happy):

const result = await quicktype({
    inputData,
    lang: 'typescript',
    inferDateTimes: false,
    alphabetizeProperties: true,
    inferEnums: false,
    rendererOptions: {
        additionalProperties: 'string',
        runtimeTypecheckIgnoreUnknownProperties: 'string',
    },
});

How to make custom URLs for different website states?

In my project I have a page where there are different directories inside other directories, which show and hide with “style.display=”block/none”, problem is that I cannot figure out how to save those states in an URL so they can be sent to others.

Ideally after user clicks on the button to “Show Section 1”, and then on “Show section 11” the URL becomes website.com/section1/section11 that he can share to others.

So question is, how do I save states of websites to be shared based on where in the directory the user is?

Example code:

JS

const Section1 = document.getElementById("section1");
const Section2 = document.getElementById("section2");
const Section11 = document.getElementById("section1-1");
const Section12 = document.getElementById("section1-2");

function show1(){
     Section1.style.display="block";
     Section2.style.display="none";
}

function show2(){
     Section1.style.display="none";
     Section2.style.display="block";
}


function show11(){
     Section11.style.display="block";
     Section12.style.display="none";

}

function show12(){
     Section11.style.display="none";
     Section12.style.display="block";

}

And so on...

HTML


<button onclick="show1()">Show Section 1</button>
<button onclick="show2()">Show Section 2</button>

<div id="section1" style="display: block">

     <button onclick="show11()">Show Section 11</button>
     <button onclick="show12()">Show Section 12</button>

     <div id="section1-1" style="display: block">

          <p>Some text</p>
          <button onclick="show111()">Show Section 111</button>
          <button onclick="show112()">Show Section 112</button>

     </div>

     <div id="section1-2" style="display: none">

          <p>Some text</p>
          <button onclick="show121()">Show Section 121</button>
          <button onclick="show122()">Show Section 122</button>

     </div>

</div>

<div id="section2" style="display: none">

<p>Something in here...</p>

</div>

Get deltaY from scroll event

I am trying to set up a project for use with mobile and desktop but the wheel event doesn’t work on mobile, so I need to use scroll.

I know how to get the deltaY from the Wheel event:

window.addEventListener("wheel", event => console.info(event.deltaY));

How do I get the deltaY from the Scroll event?

How to make the Select option appending with design?

Am making an select option from ajax success. The problem is that, the results are array so i need to manipulate the array with some html.

My appending code:

data = [['2022-02-01', '2022-02-02'],['2022-03-01', '2022-03-02'],['2022-04-01', '2022-04-02']]

$("#id_course").change(function () {
     $('select[id=id_intakes]').empty().prepend("<option></option>");
     $.each(data, function(index, name){
          $('select[id=id_intakes]').append(
              $('<option></option>').attr("value",name).text(name)
          )
    });
})

Just creates the select correctly, but it displays the array as it is. The dropdown contains all the three values array

['2022-02-01', '2022-02-02']
['2022-03-01', '2022-03-02']
['2022-04-01', '2022-04-02']

I need to manipulate this like

From:2022-02-01 & To:2022-02-02
From:2022-03-01 & To:2022-03-02
From:2022-04-01 & To:2022-04-02

So how to do this ?

Blob is returning empty string after creation

I have an extremely large JSON string that I need to send to my server. I encountered payloadTooLargeError when I tried sending the JSON string directly.

So, I decided to send it as a blob instead. But unfortunately, after creating the blob, the blob is returning an empty string.

Here is how I created the blob:

 let largeContentPayload = {
        data: {
            'batch_id': batchId,
            content: extremelyLargeJSON
        }
    };
    const largeContentStringified = JSON.stringify(largeContentPayload);
    const largeContentBlob = new Blob([largeContentStringified], {
        type: 'application/json;charset=utf-8'
    });
    console.log(largeContentBlob); //This is only returning size and type, the JSON string is not there
    const blobUrl = URL.createObjectURL(largeContentBlob);
    let requestBody = new FormData();
    let blob = await fetch(blobUrl).then(r => r.blob());
   

How can this be resolved?

Why is my Server responding with {Auth: False}?

I’ve been having this issue for a week now. I feel like I’ve wasted so much time.

I’ll tell you the issue, then what I’ve done at the end.

Right Now I’ve got both Ends on custom Domains, with Heroku hosting.

Passport Local Logs me in

2022-02-17T06:39:06.949016+00:00 heroku[router]: at=info method=OPTIONS path="/login" host=www.thehoodconservative.com request_id=ff2dc525-7feb-4a2b-afe8-41ca7cc9610e fwd="172.58.196.240" dyno=web.1 connect=0ms service=4ms status=204 bytes=369 protocol=http
2022-02-17T06:39:07.069432+00:00 app[web.1]: Logged in

From this Code

passport.use(
  new LocalStrategy(customFields, (username, password, done) => {
    User.findOne({ username: username })
      .then((user) => {
        if (!user) {
          console.log("No user");
          return done(null, false);
        } else {
          const isValid = validPassword(password, user.hash, user.salt);
          if (isValid) {
            console.log("Logged in");

            return done(null, user);
          } else {
            console.log("Wrong Password");
            return done(null, true);
          }
        }
      })
      .catch((err) => {
        done(err);
      });
  })
);

Yet I get this Response in the console

{auth: false, msg: 'Here'}

from this code on my backend

module.exports.isAuth = (req, res, next) => {
  if (req.isAuthenticated()) {
    next();
    // res.status(200).json({ user: req.user, auth: true });
  } else {
    return res.status(401).json({ auth: false, msg: "Here" });
  }
};

I have this in my Cookie storage

deviceId    D0E8508F-7685-4C9D-AFB6-522EE27A3B93    localhost   /   Session 44  

but the session in my DB doesnt show that number, it shows.

_id
:
"g3NYIQ7usEIJ5K8ETP1S-mDZImKy4Xj7"
expires
:
2022-02-18T06:50:34.597+00:00
session
:
"{"cookie":{"originalMaxAge":86400000,"expires":"2022-02-18T06:50:34.59..."

My history of aggravation

I started with Having my BE (Backend) on heroku and FE on Netlify.

Some guy on here told me its for some reasons its better to have my FE on Heroku along with BE so I did. Still same result. After hours of fussing around and changing random things and going through SOF, I read through what I saw was issues with Heroku not being able to set Cookies, somethoing about Public Suffix list. So Through a bunch of research I came to the conclusion I need to host my BE and FE on custom domains. Which I’ve done now. Yet now its the same exact issue.

I have a feeling I need lessons on debugging Cookies, but I have no idea how to do that. When I had this local, both FE and BE, It worked.

I would love it if someone showed me a better place than Heroku to host and make this work. I dont care what I have to do to get this to work.

I’m also a newbie, this is my first full stack project, without a tutorial, so I’m not sure what I need to share and dont want to spam this with too much code, just comment what you need to see, and I’ll edit this post.

Upload byte array from axios to Node server

Background

Javascript library for Microsoft Office add-ins allows you to get raw content of the DOCX file through getFileAsync() api, which returns a slice of up to 4MB in one go. You keep calling the function using a sliding window approach till you have reed entire content. I need to upload these slices to the server and the join them back to recreate the original DOCX file.

My attempt

I’m using axios on the client-side and busboy-based express-chunked-file-upload middleware on my node server. As I call getFileAsync recursively, I get a raw array of bytes that I then convert to a Blob and append to FormData before posting it to the node server. The entire thing works and I get the slice on the server. However, the chunk that gets written to the disk on the server is much larger than the blob I uploaded, normally of the order of 3 times, so it is obviously not getting what I sent.

My suspicion is that this may have to do with stream encoding, but the node middleware does not expose any options to set encoding.

Here is the current state of code:

Client-side

public sendActiveDocument(uploadAs: string, sliceSize: number): Promise<boolean> {
  return new Promise<boolean>((resolve) => {
    Office.context.document.getFileAsync(Office.FileType.Compressed,
      { sliceSize: sliceSize },

      async (result) => {
        if (result.status == Office.AsyncResultStatus.Succeeded) {

          // Get the File object from the result.
          const myFile = result.value;
          const state = {
            file: myFile,
            filename: uploadAs,
            counter: 0,
            sliceCount: myFile.sliceCount,
            chunkSize: sliceSize
          } as getFileState;

          console.log("Getting file of " + myFile.size + " bytes");
          const hash = makeId(12)
          this.getSlice(state, hash).then(resolve(true))
        } else {
          resolve(false)
        }
      })
  })
}

private async getSlice(state: getFileState, fileHash: string): Promise<boolean> {
  const result = await this.getSliceAsyncPromise(state.file, state.counter)

  if (result.status == Office.AsyncResultStatus.Succeeded) {

    const data = result.value.data;

    if (data) { 
      const formData = new FormData();
      formData.append("file", new Blob([data]), state.filename);

      const boundary = makeId(12);

      const start = state.counter * state.chunkSize
      const end = (state.counter + 1) * state.chunkSize
      const total = state.file.size

      return await Axios.post('/upload', formData, {
        headers: {
          "Content-Type": `multipart/form-data; boundary=${boundary}`,
          "file-chunk-id": fileHash,
          "file-chunk-size": state.chunkSize,
          "Content-Range": 'bytes ' + start + '-' + end + '/' + total,
        },
      }).then(async res => {
        if (res.status === 200) {
          state.counter++;

          if (state.counter < state.sliceCount) {
            return await this.getSlice(state, fileHash);
          }
          else {
            this.closeFile(state);
            return true
          }
        }
        else {
          return false
        }
      }).catch(err => {
        console.log(err)
        this.closeFile(state)
        return false
      })
    } else {
      return false
    }
  }
  else {
    console.log(result.status);
    return false
  }
}

private getSliceAsyncPromise(file: Office.File, sliceNumber: number): Promise<Office.AsyncResult<Office.Slice>> {
  return new Promise(function (resolve) {
    file.getSliceAsync(sliceNumber, result => resolve(result))
  })
}

Server-side

This code is totally from the npm package (link above), so I’m not supposed to change anything in here, but still for reference:

makeMiddleware = () => {
    return (req, res, next) => {
        const busboy = new Busboy({ headers: req.headers });
        busboy.on('file', (fieldName, file, filename, _0, _1) => {

            if (this.fileField !== fieldName) {  // Current field is not handled.
                return next();
            }

            const chunkSize = req.headers[this.chunkSizeHeader] || 500000;  // Default: 500Kb.
            const chunkId = req.headers[this.chunkIdHeader] || 'unique-file-id';  // If not specified, will reuse same chunk id.
            // NOTE: Using the same chunk id for multiple file uploads in parallel will corrupt the result.

            const contentRangeHeader = req.headers['content-range'];
            let contentRange;

            const errorMessage = util.format(
                'Invalid Content-Range header: %s', contentRangeHeader
            );

            try {
                contentRange = parse(contentRangeHeader);
            } catch (err) {
                return next(new Error(errorMessage));
            }

            if (!contentRange) {
                return next(new Error(errorMessage));
            }

            const part = contentRange.start / chunkSize;
            const partFilename = util.format('%i.part', part);

            const tmpDir = util.format('/tmp/%s', chunkId);
            this._makeSureDirExists(tmpDir);

            const partPath = path.join(tmpDir, partFilename);

            const writableStream = fs.createWriteStream(partPath);
            file.pipe(writableStream);

            file.on('end', () => {
                req.filePart = part;
                if (this._isLastPart(contentRange)) {
                    req.isLastPart = true;
                    this._buildOriginalFile(chunkId, chunkSize, contentRange, filename).then(() => {
                        next();
                    }).catch(_ => {
                        const errorMessage = 'Failed merging parts.';
                        next(new Error(errorMessage));
                    });
                } else {
                    req.isLastPart = false;
                    next();
                }
            });
        });

        req.pipe(busboy);
    };
}

How do i capture the href instead of the google? [closed]

sorry, really a newbie at this. how do i copy the href instead of google?

<a id="test" href="https://www.google.com">Google</a>
<button onclick="copyToClipboard('#test')">Copy to clipboard</button>

function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}

Supabase Not Able To pdate entire row using JSON objects

I want to update my supabase table with an object which I have got as input from the user.

I keep getting 404 Error. Is this happening cause supabase doesn’t support it yet? (RLS is disabled for now)

    const { data, error } = await supabase
      .from("company")
      .update(inputFields.values)
      .match(originalFields.values);
  };

This is what inputFields.values / originalFields.values look like.
Only the first 3 values are being updated not the entire row.

inputFields = {
    "name": "Piramal Glassed", #NEW
    "email": "[email protected]", #NEW
    "contact": "98203" #NEW
    "pin": 400066, #SAME AS ORIGINAL
    "city": "Mumbai", #SAME AS ORIGINAL
    "state": "Maharashtra", #SAME AS ORIGINAL
    "country": "India", #SAME AS ORIGINAL
}

originalFields = {
    "name": "Tata Steel",
    "email": "[email protected]",
    "contact": "982031132112"
    "pin": 400066,
    "city": "Mumbai",
    "state": "Maharashtra",
    "country": "India",
}