How to store video url in usestate and pass it to video popup modal react js

I get a response from API and pass it to the react js.

API response

    Array(80)
    0:
    Camera_Number: "Camera_1"
    Company_Name: "Fraction Analytics Limited"
    Floor Number: "Ground_Floor"
    Group_Name: "Group_1"
    Video_Name: "http://localhost:4000/video/0"
    [[Prototype]]: Object
    
    1:
    Camera_Number: "Camera_2"
    Company_Name: "Fraction Analytics Limited"
    Floor Number: "Ground_Floor"
    Group_Name: "Group_1"
    Video_Name: "http://localhost:4000/video/1"
    [[Prototype]]: Object

After getting a response populated API data to the react-ag grid.

App.js

    import video from "./video_2.mp4";
   ....... 
    export default function App(data, handleFormSubmit) {
      const { id } = data;
      const actionButton = (params) => {
        setOpen(true);
      };
      const [open, setOpen] = React.useState(false);
      const [setFormData] = useState(initialValue);
      const handleClose = () => {
        setOpen(false);
        setFormData(initialValue);
      };
      const columnDefs = [
        { headerName: "Name", field: "Company_Name", filter: "agSetColumnFilter" },
        { headerName: "Floor", field: "Floor Number" },
        { headerName: "Group", field: "Group_Name" },
        { headerName: "Camera", field: "Camera_Number" },
        { headerName: "Videos", field: "Video_Name" },
        {
          headerName: "Actions",
          field: "Video_Name",
          cellRendererFramework: (params) => (
            <div>
              <Button
                variant="contained"
                size="medium"
                color="primary"
                onClick={() => actionButton(params)}
              >
                Play
              </Button>
            </div>
          ),
        },
      ];
      const onGridReady = (params) => {
        console.log("grid is ready");
        fetch("http://localhost:8000/get_all")
          .then((resp) => resp.json())
          .then((resp) => {
            console.log(resp.results);
            params.api.applyTransaction({ add: resp.results });
          });
      };
      return (
        <div className="App">
          <div>
            <Dialog
              open={open}
              onClose={handleClose}
            >

          {/* Issue is Here */}
          <DialogContent>
            <iframe width="420" height="315" title="videos" src={video} />
          </DialogContent>
          {/* Issue is Here */}

        </Dialog>
      </div>
    </div>
  );
}

I used this code to call API and populate external API data to react js. Now the problem is to assign only one video to the source located in the project directory.

      <DialogContent>
       
       <iframe width="420" 
        height="315" 
        title="videos" 
        src={video} />
    
     </DialogContent>

Video_Name:"http://localhost:4000/video/0" , Video_Name:"http://localhost:4000/video/1"

How to assign the above multiple video URLs to the source(src) which I got from API.

Thanks

Why image and username not saved in firebase?

I have a react and firebase app wherein after successful login signup I need to display the username and the profile picture of the user.Its working until I refresh the page.After refreshing the username turns null and the profile picture is reduced to default profile Picture.Here’s the code for the same:

const Homepage = ({user,username,setusername}) => {
    const [photourl,setPhotourl]=useState(profile)
    const [photo,setPhoto]=useState(null);
    const handleImageChange=(e)=>{
       if(e.target.files[0]);
       setPhoto(e.target.files[0]);
    }
     function handleImageClick(e){
        if(photo)
        {
        const photoRef=ref(storage,photourl);
        console.log(photoRef);
         uploadBytes(photoRef,photo).then(()=>{
             getDownloadURL(photoRef).then((url)=>{
                 setPhotourl(url);
             }).catch((err)=>{
                 console.log(err);
             })
         }).catch((err)=>{
            console.log(err);
        });
        alert("Profile Image has been changed successfully. Click OK and Wait for a second to view the changes.");
        }
        else
        alert("Please upload a file")
    }
    // useEffect(()=>{
    //     if(user && user.photoURL)
    //     setphotourl(user.photoURL)
    // })
    return (
        <>
            <header>
                <nav>
                    <div className="logo"><h1 className=""><a href="#">SOLRUF</a></h1></div>
                    <div className="menu">
                            <h3>Welcome {username}</h3>   
                            <img className="avatar" src={photourl}/> 
                            <button >Change Username</button>                    
                    </div>
                </nav>
                <main>
                    <section>
                        <h3>Welcome To India</h3>
                        <h1>Do come and Visit<span className="change_content"> </span></h1>
                        <p>"India once is not enough"</p>
                        
                        <input  type="file" onChange={(e)=>{handleImageChange(e)}}/>
                        <button onClick={(e)=>{handleImageClick(e)}}>Change Profile Pic</button>   
                    </section>
                </main>
            </header>
        </>
    )
}

export default Homepage

How to manipulate date using Javascript

How can I achieve this output if user input 04-29-2022 and the
output is like this

Output:
05-14-2022
05-29-2022
06-14-2022
06-29-2022
07-14-2022
07-29-2022
08-14-2022
08-29-2022

var dateRelease = new Date("04-29-2022")

const terms = 8
for (let i = 0; i < terms; i++) {
  console.log(new Date(dateRelease.setDate(dateRelease.getDate() + 15)).toISOString().slice(0, 10))

}

JS – Can I get the next open div element – Not the sibling

Is it possible using just JS (or possibly with jQuery) to get the next open html element?

In the snippet below, if I click on any div it’ll give me the id of that div. I want it to get the next open element id, so e.g.

if I click on page123 it should give me 123efter
if I click on 123efter it should give me 13

I don’t want the next sibling within the encapsulating div, which is all I’ve managed to do so far!

document.addEventListener("click", function(event) {
console.log(event.target.id);
}
);
.efter{
min-height:20px;
}
.efter:hover{
background-color:beige;
}
<div>
  <div id="1">
    home
    <div id="1efter" class="efter"></div>
    <div id="11">
      page11
      <div id="11efter" class="efter"></div>
    </div>
    <div id="12">
      page12
      <div id="12efter" class="efter"></div>
      <div id="121">
        page121
        <div id="121efter" class="efter"></div>
      </div>
      <div id="122">
        page122
        <div id="122efter" class="efter"></div>
      </div>
      <div id="123">
        page123
        <div id="123efter" class="efter"></div>
      </div>
    </div>
    <div id="13">
      page13
      <div id="13efter" class="efter"></div>
    </div>
  </div>
</div>

Can’t get the result of an NPM library (not library specific) [duplicate]

For hours I have been trying to get this piece of code to work.

— I tried not async as well btw.

getSentenceNouns(){
    wordpos.getNouns(this.sentence, async (result) => {
        let nouns = await result;
        return nouns;
    })};

However the return value is undefinied, but if I console log inside the getNouns method I get the desired output… I tried it all, nausea kicked in, plz help.

How can I create button by using FTD? FTD is created by FifthTry – https://ftd.dev

While using FTD a new front-end language created by Fifthtry(https://www.fifthtry.com). Its easy to use for its non-technical users. Even if you don’t have any prior knowledge of html, css1 OR JavaScript you can write magical code.

Even they have collection of icons, which can be used inside button and you can create button with icons. Octicons in FTD

Package Name: https://fifthtry.github.io/button/

e.g.

  1. Primary Button
-- button: PRIMARY
role: primary
large: true
  1. Secondary Button
-- button: SECONDARY
role: secondary
large: true
  1. Button with icon
-- button: BUTTON
role: primary
large: true
icon-left: true
icon: icon.info:

Buttons created by using FTD language

FTD buttons with icon

How to define overlayMode for easyMDE?

I’ve tried to define custom mode for highlight custom markdown syntax with easyMDE like this:

CodeMirror.defineMode("mymode", function () {
  return {
    token: function (stream, state) {
      if (stream.match("aaa")) {
        return "style1";
      } else if (stream.match("bbb")) {
        return "style2";
      } else {
        stream.next();
        return null;
      }
    },
  };
});

window.easyMDE = new EasyMDE({
  element: $('#textarea')[0],
  parsingConfig: {
    allowAtxHeaderWithoutSpace: true,
  },
  overlayMode: {
    mode: CodeMirror.modes.mymode(),
    combine: true,
  },
});

Actually, CodeMirror don’t return mymode by CodeMirror.getMode('mymode') so may be there mistake in declaration by CodeMirror.defineMode in my code.

How to show and hide loader while using fetch in JavaScript?

I’m using JavaScript Fetch to access an API and I want to show a loader while the fetch is in progress. I’m using the following code…

      async function fetchStates() {
            showLoader();
            await fetch('https://localhost:7123/locations/states?token=@{@HttpContext.Session.GetString("sessionToken")}')
            .then(response => response.json())
            .then(states => {
                for (let i = 0;i < states.length;i++){
                    let option = document.createElement('option');
                    option.text = states[i].name;
                    option.value = states[i].id;
                    ddlCAStates.appendChild(option)
                }
                /*hideLoader(1);
                scrollToTop(1);*/
            })
            .catch(error => {
                divErrors.style.display = "block";
                let errorName = GetHttpErrorName(error.toString());
    
                txtErrors.textContent = 'The server responded with error: ' + error + ' ' + errorName;
                /*hideLoader(2);
                scrollToTop(2);*/
            })
            .finally(() => {
                hideLoader();
                scrollToTop();
            });
        }

    function showLoader() {
        document.getElementById('loader').style.display = 'block';
    }

    function hideLoader() {
        document.getElementById('loader').style.display = 'none';
    }

    function scrollToTop() {
        document.body.scrollTop = 0; // For Safari
        document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
    }

The loader displays for a split second and then hides way before the fetch is completed. The loader should be visible until either the fetch successfully loads data or it fails for any reason. What I’m doing wrong here?

Failed to traverse DOM while rendered inside iframe with section tags

I facing a situation which i can’t traverse the dom inside iframe. My code is as follows. When i am trying to accessing childNodes of body tag, console will show there are no childNodes inside the body tag.

<!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>
</head>

<body>
    <iframe id="container"
        src="./resources/c07.xhtml"
        frameborder="0"></iframe>
    <style>
        #container {
            width: 100%;
            height: 800px;
        }
    </style>
    <script src="index.js"></script>
</body>
</html>

c07.xhtml

<!DOCTYPE html>
<html>
<body>

<h1>The section element</h1>

<section>
  <h2>History</h2>
  <p>The World Wide Fund for Nature (WWF)</p>
</section>

<section>
  <h2>Symbol</h2>
  <p>The Panda has become the symbol of WWF.</p>
</section>

</body>
</html>

//index.js

const parentNode = document.querySelector("#container");
const iframeBody =  iframeRef(parentNode);
console.log(element.childNodes[0].getElementsByTagName('section')); //prints HTMLCollection[] and length is 0

function iframeRef( frameRef ) {
    return frameRef.contentWindow
        ? frameRef.contentWindow.document
        : frameRef.contentDocument
}

How can i resolve this?

How to make smooth animation?

I want to make smooth animation of appearing and disappearing a block of text. It appears smoothly but disappears very fast. How can I make it smooth?

Here is the CSS code:

.question-header > * {
  margin-bottom: 15px;
}

.question-header > * {
  margin-top: 20px;
}
.question-header {
  position: relative;
  border-bottom: 1px solid #e0e0e0;
}

.question-header.add-padding {
  padding-bottom: 30px;
}

.add-padding {
  padding-bottom: 30px;
}

.question-header h3 {
  width: 701px;

  font-weight: 600;
  font-size: 25px;
  line-height: 130%;
  color: #101828;
}

.plus-sign {
  position: absolute;
  right: 0;
  top: -20px;
  cursor: pointer;
}

.answer-to-questions.display {
  max-width: 630px;
  position: sticky;
  opacity: 1;
  transform: translateY(5%);
}

.answer-to-questions {
  position: absolute;
  opacity: 0;
  transform: translateY(-20%);
  transition: all 0.2s ease-in;
}
const answer = document.querySelector(".answer-to-questions");

const plusSign = document.querySelector(".plus-sign");

const questionHeader = document.querySelector(".question-header");

// plusSign.forEach((item)=>{

//     // item.addEventListener('click',()=>{
//     //     answer.classList.toggle('display');
//     // })

// })

plusSign.addEventListener("click", () => {
  answer.classList.toggle("display");
  questionHeader.classList.add("add-padding");

  if (answer.classList.contains("display")) {
    plusSign.src = "../images/plus-close.svg";
  } else {
    plusSign.src = "../images/plus.svg";
    questionHeader.classList.remove("add-padding");
  }
});

And my HTML:

<!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>
    <div class="question-header">
      <h3>Have you built an App similar to mine?</h3>
      <img class="plus-sign" src="./images/plus.svg" alt="" srcset="" />

      <div class="answer-to-questions">
        <p>
          Since 2010, we've successfully implemented 160+ projects for
          industries like E-Commerce, the Internet of Things, Digital music
          distribution, E-Learning, and many more. Since 2010, we've
          successfully implemented 160+ projects for industries like E-Commerce,
          the Internet of Things, Digital music distribution, E-Learning, and
          many more.
        </p>
      </div>
    </div>

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

Here is the link to code sandbox https://codesandbox.io/s/cocky-monad-se1m22?file=/index.html:0-1010 .

Hopefully, I made this clear. Thank you everyone in advance!

get Firebase database

I am trying to get and show my data from the firebase database to the HTML page in a table form, but no output showing. I attached a screenshot of my database below. I have been trying for like days and can’t solve it. Can someone help me to point out what my problem is? For security purposes, I erased the details of my firebase configuration there.

    <body>

        <table>
            <thead>
                <th>Sno</th>
                <th>First Name</th>
                <th>Second Name</th>
                <th>Email</th>
                <th>LastLogin</th>
                <th>Confirm Password</th>

            </thead>
            <tbody id="tbody1">
        
            </tbody>
        </table>
        <script src="https://www.gstatic.com/firebasejs/8.6.8/firebase-app.js"></script>
        <script src="https://www.gstatic.com/firebasejs/8.6.8/firebase-auth.js"></script>
        <script src="https://www.gstatic.com/firebasejs/8.6.8/firebase-database.js"></script>

        <script id="MainScript">

                    var firebaseConfig = {
                    apiKey: "",
                    authDomain: "",
                    projectId: "",
                    storageBucket: "",
                    messagingSenderId: "",
                    appId: "",
                    measurementId: ""
                    };

                    firebase.initializeApp(firebaseConfig);

        
//---------------------GET ALL DATA-------------------------------//

        function SelectAllData(){
            firebase.database().ref('admins').once('value',
            function(AllRecords){
                AllRecords.forEach(
                    function(CurrentRecord){
                        var firstName = CurrentRecord.val().first_name;
                        var secondName = CurrentRecord.val().second_name;
                        var  email= CurrentRecord.val().email;
                        var lastLogin = CurrentRecord.val().last_login;
                        var conpassword = CurrentRecord.val().confirm_password;
                        AddItemsToTable(firstName,secondName,email,lastLogin,conpassword);
                    }
                );
            });
        }

        window.onload = SelectAllData;
//------------------filling the table-------------------//
        var stdNo = 0;
        function AddItemsToTable(firstName,secondName,email,lastLogin,conpassword){
            var tbody = document.getElementById('tbody1');
            var trow = document.createElementById('tr');
            var td1 = document.createElementById('td');
            var td2 = document.createElementById('td');
            var td3 = document.createElementById('td');
            var td4 = document.createElementById('td');
            var td5 = document.createElementById('td');
            var td6 = document.createElementById('td');

            td1.innerHTML= ++stdNo;
            td2.innerHTML= firstName;
            td3.innerHTML= secondName;
            td4.innerHTML= email;
            td5.innerHTML= lastLogin;
            td6.innerHTML= conpassword;

            trow.appendChild(td1); 
            trow.appendChild(td2); 
            trow.appendChild(td3); 
            trow.appendChild(td4); 
            trow.appendChild(td5);
            trow.appendChild(td6);
            


            tbody.appendChild(trow);
            
        }

    </script>
    </body>

enter image description here

The way I pushed the data into database

// Set up our register function
  function register () {
    // Get all our input fields
    email = document.getElementById('email').value
    password = document.getElementById('password').value
    first_name = document.getElementById('first_name').value
    second_name = document.getElementById('second_name').value
    confirm_password = document.getElementById('confirm_password').value
  
    // Validate input fields
    if (validate_email(email) == false || validate_password(password) == false) {
      alert('Email or Password is Outta Line!!')
      return
      // Don't continue running the code
    }
    if (validate_field(first_name) == false || validate_field(second_name) == false || validate_field(confirm_password) == false) {
      alert('One or More Extra Fields is Outta Line!!')
      return
    }
   
    // Move on with Auth
    auth.createUserWithEmailAndPassword(email, password)
    .then(function() {
      // Declare admin variable
      var user = auth.currentUser
  
      // Add this admin to Firebase Database
      var database_ref = database.ref()
  
      // Create Admin data
      var user_data = {
        email : email,
        first_name : first_name,
        second_name : second_name,
        confirm_password : confirm_password,
        last_login : Date.now()
      }
  
      // Push to Firebase Database
      database_ref.child('admins/' + user.uid).set(user_data)
  
      // DOne
      alert('Admin Account Created!!')
      window.location = "login.html";
      
    })
    .catch(function(error) {
      // Firebase will use this to alert of its errors
      var error_code = error.code
      var error_message = error.message
  
      alert(error_message)
    });
    

}

Why is the background color of my MUI TextField changing after I enter data and how do I prevent that?

I have a TextField inside a FormControl inside a Styled Control (Paper) that looks like this:

const StyledPaper = styled(Paper)(({ theme }) => ({
  backgroundColor: "#99d6ff",
  width: '90%',
  justify: 'center',
  textAlign: 'center'
}));
...
<StyledPaper square={false} >
  <FormControl variant="filled" fullWidth>
    <TextField
      id="loginInput"
      label="Login"
      InputLabelProps={{ shrink: true }}
      value={login}
      onChange={() => handleInputChange("loginInput")} />
  </FormControl>
</StyledPaper>

The problem I’m having here is that when you select the TextField and fill it with an autocomplete, the background changes to white (the color of the autocomplete background). If I just type and don’t use the autocomplete the background remains as I intended from the StyledPaper. How can I prevent the background color change?

Using spread operator to update dictionary value which is an object array

I am trying to save an API payload to a dictionary. The API data model has the attributes “category”, “id” and “name”.

let apiPayload = [];

(async () => {
  let fetchValue = await
  fetch('https://asia-southeast1-citric-pager-319712.cloudfunctions.net/gcp-simple-api').then(response => {
    if (response.ok) {
      return response.json();
    }
    throw response;
  }).then(data => {
    return data;
  }).catch(error => console.log(error));

  console.log('fetchValue', fetchValue);

  let dictionary = Object.assign({}, ...fetchValue.map((x) => ({
    [x.category]: [x]
  })));
  console.log('dictionary', dictionary);
})();

How do I append new category object in my dictionary so that it is sorted by category with category objects, e.g.

HTML: [{
  category: "HTML",
  id: "blog-post",
  name: "Blog Post"
}, {...}, {...}],
JavaScript: [{
  category: "JavaScript",
  id: "curry",
  name: "Curry"}, {...}, {...}]