React Update/Edit Field not updating after mutation?

I have a same field for creating and updating the form using modal , the creation is working fine, while for the updating the latest changes are not updating , infact I am getting the previous value only , let me know where I am missing here .

Creation and Updating:

  const createVendor = async () => {
    setEditMode(false);
    const data = { contactPerson, contactNumber, email };
    try {
      const response = await addingVendor(data);
      setMessage(response.data.message);
      forceUpdate(), handleClose();
    } catch (error) {
      throw error;
    }
  };

const updateVendor = async () => {
    setEditMode(true);
    const data = { contactPerson, contactNumber, email };
    try {
      const response = await updatingVendor(vendorId, data);
      console.log(response);
      setMessage(response.data.message);
      forceUpdate(), handleClose();
    } catch (error) {
      throw error;
    }
  }; 

This is where I am triggering the modal for update:

 const [inputValue, setInputValue] = useState({
    contactPerson: '',
    contactNumber: '',
    email: '',
  });

      const showUpdateVendor = (data) => {
        setOpenUpdate(true);
        setInputValue({
          contactPerson: data.contactPerson,
          contactNumber: data.contactNumber,
          email: data.email,
        });
        setVendorId(data._id);
      };

and here is the modal component where i am passing via props:

<SideModal
  {...inputValue}
  open={openUpdate}
  onClose={() => setOpenUpdate(!openUpdate)}
  title='Update Vendor'
  handleChange={handleChange}
  editMode={editMode}
  onSubmit={updateVendor}
  isLoading={isupdatingVendor}
/>

What is standard approach to implement login page common across different organizational websites?

I want to develop a “common” login page for all different websites that our organization offers. That is user should be able to log in only with a single username and password and be able to access all different organizational sites allowed to him.

I can develop a React login page. But what is the “standard or common” approach followed in the Industry to make this login page common across different sites? Should I do some kind of redirection if the user is not logged in and is trying to access a webpage requiring being logged in? If yes, how? If not, what else?

How to spy on callback of childProcess.exec using jest

I’m trying to see what the error, stdout and stderr of a childProcess callback is. I have this at the moment:

let childProcCallbackSpy;
jest.spyOn(childProcess, "exec").mockImplementationOnce((command, callback) => {
    if (command === "intended command") {
        childProcCallbackSpy = jest.spyOn(callback);
        jest.requireActual(childProcess).exec(command, callback);
    }
});
objToTest.methodWithChildProc((functionCallbackOutput) => {
    if (childProcCallbackSpy.mock.calls[0].includes("wanted arg")) {
        doThing1();
    } else {
        doThing2();
    }
});

The problem is that running the test that contains this gives the following error, referring to the line where the value of childProcCallbackSpy is set:

“Cannot spy the undefined property because it is not a function; undefined given instead”

How to use Lazy query with React-query?

I am using React-query for my API calls. I am wondering if there is a way to call the query in a lazy way.

Meaning to call the query only when a query param changes.

This is what I currently have; I am using a hack with the “useEffect” where if recipeName changes, then run the refetch function.

  const [recipeName, setRecipeName] = useState("");

  const { data, refetch } = useQuery(
    "homePageSearchQuery",
    () => searchRecipeByName(recipeName),
    { enabled: false }
  );

// HACK
  useEffect(() => {
    if (!!recipeName) {
      refetch();
    }
  }, [recipeName]);

  const handleOnSearchSubmit = async (recipeSearch: RecipeSearch) => {
    setRecipeName(recipeSearch.search);
  };

Preferably, I would like to call the query in the “handleOnSearchSubmit” function.

I could create a custom useLazyQuery hook to handle this, but I’m wondering if React-query has a native way to handle this.

Get next month from current date in html using javascript

I want to display a p tag with the next month, for example now is December But the p tag should be display January, If we in Jan the p tag should be display Febrary. What I have until now is this.

const month = ["January","February","March","April","May","June","July","August","September","October","November","December"];

const d = new Date();
let name = month[d.getMonth()];
document.getElementById("currentmonth").innerHTML = name;
<!DOCTYPE html>
<html>
<body>
<p id="currentmonth"></p>
<p id="nextmonth"></p>

</body>
</html>

How can we display multiple polygons on google Map without Center of Map (LAT and LNG)?

I have a one dropdown and each dropdown value is having latitude and longitude and when I select values in dropdown, I need to display the polygons with help of latitude and longitude , so I done with filter function and displaying the polygons but now the problem is I don’t have the Map center(Lat and lag) and zoom , so I used the LatLngBounds() to zoom all polygons but while selecting the dropdown initial time map is not zooming to polygon (Its displaying polygons as small size with duplications) but when I select another dropdown value its working fine as expected, I am not getting any idea on these issue.

I am attaching stackblitz URL for reference :- https://stackblitz.com/edit/primeng-multiselect-demo-czacgs?file=src%2Fapp%2Fapp.component.ts

Please help me on these problem,

Thanks in advance.

DiscordAPIError: Unknown Interaction

I have been using an online guide to set up a currency bot but when I use the command to add items to the shop the terminal throws out this error and while the bot says the item has been added when I check the shop it has nothing in it. this is the exact error that i get I’m new to coding and a have little to no idea what it means any help or point towards a guide that might explain it would be greatly appreciated

DiscordAPIError: Unknown interaction
    at RequestHandler.execute (c:UsersdanieDesktopCurrencyBotnode_modulesdiscord.jssrcrestRequestHandler.js:349:13)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async RequestHandler.push (c:UsersdanieDesktopCurrencyBotnode_modulesdiscord.jssrcrestRequestHandler.js:50:14)
    at async CommandInteraction.reply (c:UsersdanieDesktopCurrencyBotnode_modulesdiscord.jssrcstructuresinterfacesInteractionResponses.js:99:5)
====================

How can I use websockets with Node.js to send something to one client after recieving a message from another?

I am very new to node and javscript and am trying to make a basic program that sends whatever is in a textbox and if you open the website on another pc you can enter something else into the textbox and it changes it on the first pc.
Here is my code on the server side

    var fs = require("fs");//get fs so we can read text files
const WebSocket = require('ws');//get websockets to communicate
const express = require('express');

const app = express();
// Set up server
const wss = new WebSocket.Server({ port: 8080 });

// Wire up some logic for the connection event (when a client connects) 
wss.on('connection', function connection(ws) {

// Wire up logic for the message event (when a client sends something)
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);

    fs.writeFile("message.txt", message, (err) => {
    if (err) console.log(err);
    


});
  });

  // Send a message
  //ws.send('server message sent to client on start');
});

app.get('/', (request, response) => {
    //readFile('./home.html', 'utf8', (err,html) => {
        response.sendFile('C:\Users\(myUserName)\Desktop\Coding\javascript\wstest.html');


    });

app.listen(process.env.PORT || 3000, () => console.log('App avaliable on http://localhost:3000'))'

and heres the code on the client side

<!DOCTYPE html>
<html>
<body>

<h1>Text communicator javascript edition (:</h1>



<input type="text" placeholder="Enter message" oninput="changeVal()">
<p id="p1">Hello World!</p>
</html>

<script>// Create WebSocket connection.
function changeVal() {
  const val = document.querySelector('input').value;
  socket.send(val);
}
const socket = new WebSocket('ws://localhost:8080');

// Connection opened
socket.addEventListener('open', function (event) {
    socket.send('hi');
});

// Listen for messages
socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
    document.querySelector('input').value = event.data
    document.getElementById("p1").innerHTML = event.data;
});
</script>

So how can I make the server send a websocket message to both clients after receiving a message from one?

Visual Studio debugging Javascript with JSON data

I have some simple test code to prove out this weird behavior. The program runs without breakpoints. But if I set a breakpoint, it stops someplace in the json data and I can’t single-step to debug my code. If I remove the json data, the breakpoints stop and I can single step from there (F10). Weird.

Here is my HTML code:

 <!DOCTYPE html>
 <html>
 <head>
 <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
 <title>JSON Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

</head>
<body>

<div id="header">
    <h2>JSON Test</h2>

    <label for="HostName">Your Node Name:</label>
    <label id="HostName" style="width: 600px;"></label> 
    <label id="Status" style="text-align: center;"></label>
    <input type="button" id="btnRefresh" value="Refresh Me" />

</div>

<script type="text/javascript">
    $(document).ready(function () {

        alert("Ready");

        alert(data.name);
    })
</script>

<script type="text/javascript">
    var data = {
        "id": 1,
        "name": "abc",
        "address": {
            "streetName": "cde",
            "streetId": 2
        }
    }
</script>
</body>
</html>

If you get the same results then it’s an issue in Visual Studio. If not, then could it be in my version of VS 2017?? Weird.

Images have a lot of space between them inside a ScrollView in React Native

A Horizontal ScrollView with the images

<ScrollView contentContainerStyle={styles.contentContainer} horizontal={true} showsHorizontalScrollIndicator={false}>
      <Image source={require("../assets/images/raisins_and_banana.png")} />
      <Image source={require("../assets/images/yogurt_with_fruits.png")} />
      <Image source={require("../assets/images/pie.png")} />
</ScrollView>

This is my StyleSheet

const styles = StyleSheet.create({
  contentContainer: {
    alignItems:'center',
  },
});

Currently it looks like this

Currently looks like this

I want it to look like this

I want it to look like this

Discord OAUTH error: ‘unsupported_grant_type’,

I am trying to implement a Discord-Login onto my Website. Unfortunately I am getting an error from discord.

Does anybody see, whats wrong with my code?

FYI: I am already get back the code from discord. So my first request is working fine.

What I want to do with the Data:

I want to get the user_ID so I can add groups to the user on my Discord Server.

ERROR:

error: 'unsupported_grant_type',
error_description: 'Grant type None is not supported'

Code:

router.get('/account-settings/connections/discord/callback', (async (req, res) => {

  const code = await req.query.code;
  const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);

  fetch(`https://discordapp.com/api/oauth2/token`, {
          method: "POST",
          headers: {
              Authorization: `Basic ${creds}`,
          },
          body: querystring.stringify({
              grant_type: 'authorization_code',
              code: code,
              redirect_uri: dis_redirect
          }),
      })
      .then((res) => res.json())
      .then((body) => console.log(body));
})

Thank you very much in advance!!!

The best regards,
Joshy

How to clear TextField in react?

Hi everyone i have a question regarding on how to clear TextField after clicking the icon? thanks

const [filteredLocations, setFilteredLocations] = useState(locations);

const clearSearch = () => {
    // i dont know what should i put here TextField.clear() or so what ever
  };
  const filterResults = (e) => {
    ....
    setFilteredLocations(filteredLocations);
  };

    <TextField
      placeholder="Search Locations"
      onChange={filterResults}
      InputProps={{
        endAdornment: (
          <IconButton onClick={clearSearch} edge="end">
            <ClearIcon />
          </IconButton>
        )
      }}
    />

Youtube is not counting views from Youtube iframe from our web app

Issue: The Vuejs YouTube-iframe(vue-youtube) in our web application uses the sample code below. When the user plays the video, the view count on the YouTube channel doesn’t get updated. Though our website shows up in the list of viewers for the channel, the view count contributions from our website is 0. Findings so far When tested from localhost and DEV(internal purpose) the youtube view count is updated .When used from our domain site, the YouTube viewers count doesn’t update.

Bundler:
import VueYoutube from 'vue-youtube'
Vue.use(VueYoutube)

<template>
   <youtube id="youtube" :video-id="embedId" ref="youtube" :player-vars="playerVars" disablepictureinpicture controlslist="nodownload" fitParent muted @ready="onReady" @playing="playing" @paused="paused"/>
</template>
 
<script>
export default {
        data() {
        return {
        playerVars: {
            autoplay: 0,
            controls: 0,
            enablejsapi: 1,
            rel: 0,
            start: 0,
            modestbranding: 1,
            showsearch: 0,
            playsinline: 1,
},
  
computed: {
    player() {
            return this.$refs.youtube.player
        }
}
methods: {
        playVideo() {
            this.player.playVideo()
        },
}
</script>

CSS animation – HTML/CSS

I have the following code:

/* Contact Form */

input[type=text],
[type=email],
select,
textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #555;
  margin-top: 6px;
  margin-bottom: 16px;
  resize: vertical;
}

input[type=submit] {
  background-color: #0563bb;
  color: white;
  padding: 12px 20px;
  border: none;
  cursor: pointer;
}

input[type=submit]:hover {
  opacity: 0.9;
}

.contactform {
  position: relative;
  border-radius: 50px;
  background-color: #f2f2f2;
  padding: 5px;
  z-index: 2;
  display: block;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: auto;
  margin-top: 1%;
  width: 100%;
  animation-name: gradient;
  animation-duration: 3s;
  animation-iteration-count: infinite;
}

.contactform:hover {
  animation-name: gradient;
  animation-duration: 15s;
  animation-iteration-count: infinite;
}

.column {
  float: center;
  width: 50%;
  margin-top: 6px;
  padding: 20px;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

.row:after {
  content: "";
  display: table;
  clear: both;
}

@media screen and (max-width: 600px) {
  .column,
  input[type=submit] {
    width: auto;
    margin-top: 0;
  }
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}
<section id="contact">
  <div class="container" data-aos="fade-up">
    <div class="contactform">
      <div style="text-align:center">
        <div class="section-title">
          <h2><br/>Get In Touch</h2>
        </div>
        <p>Feel Free To Reach Out To Me Through This Form! </p>
      </div>
      <div class="row">
        <div class="column">
          <form name="myform" action="thankyou.html" method="POST" novalidate>
            <label for="firstname">First Name</label>
            <input type="text" id="first name" name="firstname" placeholder="Your First Name.." required>
            <label for="lastname">Last Name</label>
            <input type="text" id="lastname" name="lastname" placeholder="Your Last Name.." required>
            <label for="email">Email:</label>
            <input type="email" id="email" name="email" placeholder="Your Email.." required>
            <label for="subject">Subject</label>
            <textarea id="subject" name="subject" placeholder="Lets Collaborate.." style="height:170px" required></textarea>
            <input type="submit" value="Submit">
          </form>
        </div>
      </div>
    </div>
  </div>
</section>

I basically want to add an animation where I want to add an animation on the input fields. Basically, I want my expected output to be like this:

* {
  --input-height: 3rem;
}

section {
  height: 100vh;
  width: 100vw;
  display: grid;
  place-content: center;
}

.input-container input {
  height: var(--input-height);
  width: 80vw;
  font-size: 2rem;
}

.input-container {
  position: relative;
  display: grid;
  place-items: center start;
}

.input-container label {
  position: absolute;
  left: 1rem;
  font-size: 1.5rem;
  color: rgb(90, 90, 90);
  background-color: white;
  transition-duration: 0.5s;
}

.input-container input:focus~label {
  position: absolute;
  font-size: 0.7rem;
  top: -0.6rem;
  padding: 0.2em;
  left: 0.5rem;
  color: rgb(0, 81, 255);
  background-color: white;
  transition-duration: 0.2s;
  z-index: 2;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <section>
    <form action="">
      <div class="input-container">
        <input type="text" name="" id="my-input">
        <label for="my-input">hello world</label>
      </div>
    </form>
  </section>
</body>

</html>

As you can see, when you click the input field the text shortens and gets aligned on top of the input field. I would like this but with the contact form I have above. How would I incorporate this code above into the contact form code I sent before? I tried using the same logic but got stuck since my code that I sent at the very top is a bit different than what I sent directly above. Any suggestions on how I can accomplish this task? Any help will be highly appreciated!

How do I create an overlay in React?

I am currently trying to create an overlay on an image when hovering. I am able to get a box displayed on screen but it’s not placed over the image.

featured.js

const Featured = ({ images }) => {
  if (!images || !Array.isArray(images)) return null;

  return (
    <section className={styles.featuredWrapper} id="work">
      {images.map((image) => {
        return (
          <div className={styles.wrap}>
            <GatsbyImage
              image={image.gatsbyImageData}
              alt="Link to the alt text"
              className={styles.featuredImg}
            />
            <div className={styles.featuredOverlay}>Test</div>
          </div>
        );
      })}
    </section>
  );
};

featured.module.css

.featuredImg {
  width: 100%;
  position: relative;
}

.featuredOverlay {
  position: absolute;
  background: black;
  opacity: 0.5;
  width: 100%;
  height: 100%;
  z-index: 1;
}

Every explanation I see revolves around the use of positions absolute and relative which makes me think my issue is how I am rendering my component. Am I using the position properties on the wrong elements?