How to make API data a link once fetched to take user to another page to display data

I am trying to make a API call and return the JSON object in an unordered list in Component A. Once I make the unordered list, I need to make the name property a link which will take me to component B and show the data related to the name property. How can I achieve this?

Component A (Home.js)


import React , { useState} from "react";
import axios from 'axios'; 
import Display from './Display'

function Home(){

  const [info, setInfo] = useState([]);
  const [orgName, setOrg] = useState([]);
  const [dataToMove, setDataToMove] = useState([]);

  let signal = axios.CancelToken.source();

  function handleChange(event) {
      setOrg(event.target.value);
  }

  function handleClick(event) {
      axios.get(`https:/api.github.com/orgs/${orgName}/repos`, {
          cancelToken: signal.token,
      })
          .then(res => {
              const info = res.data;
              setInfo(info);
              setDataToMove(info);
              console.log(info);
          }).catch(err => {
          console.log(err);
      });
  }
//  < Display parentToChild={this.state.dataToMove}>
//|Image: <img src={dummy.owner.avatar_url} alt="" />
  const parentToChild = () => {
    let data ={};
    data = dataToMove;
  }
  let getInfo = info;
    return (
      
        <div>
           
          <span>Enter User Id</span>
               <input type="text" onChange={handleChange}/>
               <button onClick={handleClick}>Get Posts By User</button>
               <button onClick={parentToChild} > Go to Display Page</button>
               <ul> 
             {
              getInfo.map(dummy => 
               (
                 <li key={dummy.id} >
                       Name: {dummy.name}  
                     
                       || Fork: {dummy.fork ? "true" : "false"} || Owner: {dummy.owner.login}
                       || Avatar: {} || Open Issues: {dummy.open_issues_count}} 
    
                           </li>
                    
               ))
    
             }
           </ul>
         
        </div>
       
                       
              
       );
}

export default Home;


Component B (Display.js)


function Display({parentToChild}){
  const info =[];

    return (
      
        <div>
          <span>See Data Below</span>
               
               <ul> 
             {
              info.map(dummy => 
               (
                     <li key={dummy.id} >
                       Name: {dummy.name} 
                     
                       || Fork: {dummy.fork ? "true" : "false"} || Owner: {dummy.owner.login}
                       || Avatar: {} || Open Issues: {dummy.open_issues_count}} ||Image: <img src={dummy.owner.avatar_url} alt=""/>
    
                           </li>
                                      
                         
               ))
    
             }
           </ul>
              <p> {parentToChild}</p>
        </div>
                       
              
       );
}

export default Display;

Navigation.js

import React from "react";
import { NavLink } from "react-router-dom";

function Navigation() {
  return (
    <div className="navigation">
      <nav className="navbar navbar-expand navbar-dark bg-dark">
        <div className="container">
          <NavLink className="navbar-brand" to="/">
            React Multi-Page Website
          </NavLink>
          <div>
            <ul className="navbar-nav ml-auto">
              <li className="nav-item">
                <NavLink className="nav-link" to="/">
                  Home
                  <span className="sr-only">(current)</span>
                </NavLink>
              </li>
              <li className="nav-item">
                <NavLink className="nav-link" to="/about">
                 Display Data
                </NavLink>
              </li>
            </ul>
          </div>
        </div>
      </nav>
    </div>
  );
}

export default Navigation;

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import  {Navigation, Display, Home }from './Components';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
  <Router>
    <Navigation />
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/Display" element={<Display />} />
    </Routes>
  </Router>
  </React.StrictMode>
);



Insert Google Block Ads with Javascript

I have a site with many pages and I want to start with Google Ads on it… so I want to insert ads to all the pages, but I want to find a good way… I don’t want to add the code manually in all the files… so I tried to build a function to add the google’s adsense block after some paragraphs using javascript:

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXX" crossorigin="anonymous"></script>

var display_block = '<ins class="adsbygoogle"' +
        'style="display:block"' +
        'data-ad-client="ca-pub-XXXXX"' +
        'data-ad-slot="xxxxxxxxxx"' +
        'data-ad-format="auto"' +
        'data-full-width-responsive="true"></ins>' +
        '<script>' +
        '(adsbygoogle = window.adsbygoogle || []).push({});' +
        '</script>';

    var afterparagraph1 = document.getElementById('article').getElementsByTagName('p')[0]
    afterparagraph1.insertAdjacentHTML('afterend', display_block );

    var afterparagraph3 = document.getElementById('article').getElementsByTagName('p')[3]
    afterparagraph3.insertAdjacentHTML('afterend', display_block );

Well the code is added (I can see when inspect with console) but the ads doesn´t appear… but if I insert the code manually inside each html file it appears… 🙁

Do you know what I am doing wrong?

Thanks for your time 🙂

How to Add a Decimal Number to a Variable Value? [duplicate]

How could you go about adding a decimal value to the total value of a variable?

Expected Result: 0 -> 0.1 -> 0.2

Result: 0 -> 0.1 -> 0.10.1 -> 0.10.10.1

<button id="practice" type = "button" Style="font-size: 25px; margin-left: 10px; width:200px;">Example<br><span style="font-size:15px;"><span id="practicemultiplier">0</span>X Multiplier <br> Cost: <span id="practicecost">1</span> hearts</span></button>

<script>
    var practice=document.getElementById("practice")
    practice.onclick=function(){
        var practicemultiplier = localStorage.getItem("practicemultiplier");
        practicemultiplier = practicemultiplier + 0.1 
        document.getElementById("practicemultiplier").innerHTML = practicemultiplier;
        localStorage.setItem("practicemultiplier", practicemultiplier);
    }
</script>

Google maps marker clusterer zooms in with page jump on click

This is an issue in the google documentation for marker clusterer as well as my code and I’ve been requested to fix the zoom jump to a smooth transition zoom while also centering. You can see in the google link occasionally it will smooth zoom but on certain aspect ratios it will jump to the zoom level upon click to decluster.

I’ve tried changing MarkerClusterer to MarkerClustererPlus and that didn’t seem to resolve the issue. I also tried an event listener on the cluster click to slowly add increments of zooms but seems to not work either even with zoomOnClick set to false.

    google.maps.event.addListener(markerClusterer, "clusterclick", function (cluster) {
  let center = cluster.getCenter();
  map.panTo(center.latLng);
  smoothZoom(map, 10, map.getZoom(), center);
})


    function smoothZoom(map: google.maps.Map, markerZoom: number, cnt: number) {
  if (cnt ? cnt >= markerZoom : null) {
    return;
  } else {
    let z = google.maps.event.addListener(map, "zoom_changed", function (event) {
      google.maps.event.removeListener(z);
      smoothZoom(map, markerZoom, cnt ? cnt + 1 : cnt);
    });

    setTimeout(function () {
      map.setZoom(cnt ? cnt : 0);
    }, 80);
  }
}

Just a side note: this is my first ever question on stackoverflow so please bare with me.

Javascripy: how to read variable values that have been declared inside a string [duplicate]

So basically, I want to read the value of a variable that was been declared in a string

str = '?name=name&number=7'

Let’s say that was the string in which the variables are stored.
I want to have 2 different variables afterward like so:

name = 'name'
number = 7

I have tried splitting it into arrays and using for loops to read the exact values, but I think I’m doing something wrong or there is an easier approach.

Note: the string would be user input, so there are no set amount of characters that the string will contain.

How to force relative source map URL to follow redirect

I have a package parse-ingredient, which has a demo page here. The demo page depends on another of my packages called numeric-quantity. The demo page just fetches the latest UMD versions of each package from UNPKG like this:

<script src="https://unpkg.com/numeric-quantity"></script>
<script src="https://unpkg.com/parse-ingredient"></script>

Each package has a source map identified as a relative URL, like this (abbreviated version of numeric-quantity.umd.js):

(function(n,d){typeof exports=="object"&&typeof module!="undefined"? // ...etc, etc, etc
//# sourceMappingURL=numeric-quantity.umd.js.map

When the demo page is loaded in Chrome, this appears in the console:

DevTools failed to load source map: Could not load content for https://unpkg.com/numeric-quantity.umd.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE

Similar errors appear in other browsers. I believe this is because the browser thinks that since the original requested URL is https://unpkg.com/numeric-quantity, then the sourceMappingURL should be relative to that location, not the redirect URL that UNPKG actually resolves to (https://unpkg.com/browse/[email protected]/dist/numeric-quantity.umd.js).

Is this something I can fix with configuration? If not, is it a problem UNPKG can fix? And if not that, then is this something the browsers are actually doing wrong?

Relevant UNPKG GitHub issue

Is there a way of running an if statement on whether or not props have changed in React with data stored in Redux

I currently have a component that holds a posts array, this component takes in a prop called sortBy which tells the component to either fetch data sorted by popular or new. The way my component is set up is upon initialization the posts are fetched then stored in redux, I only get new posts if my posts is empty. That way I’m not constantly fetching new data.

const posts = useSelector((state) => state.posts.posts);
useEffect(() => {
    const { sortby } = props;
                            // here I would like to check if props has changed
    if (Object.keys(posts).length === 0) {
      dispatch(getPostsAsync(sortby)).then((response) => {
        setLoading(false);
      });
    }
  }, [dispatch, props, posts]);

Now I would like to check if the sortBy props has changed value. So originally it might be sortby='-numLikes' but when I sortby ‘new’ it should then be sortby='-createdAt' after it changes I would like to tell Redux to fetch new data.

How to delete a row from database with a Bootstrap Modal on html page?

I want to delete a row from the database with the modal for confirmation of deleting the row here is the part of the php I have

    <div class="container col-sm col-md col-lg col-xl" id="header">
    <table class="table table-bordered" id="myList">
        <thead>
        <tr>
            <th>S.No</th>
            <th>Name</th>
            <th>Email</th>
            <th>Rating</th>
            <th>Review</th>
            <th>Image</th>
            <th>Suggestion</th>
            <th>NPS</th>
            <th>Delete</th>
        </tr>
        </thead>
        <tbody class="table-warning" id="myList">
    
    <?php
    include 'database_conn.php';      // makes db connection
    
    $sql = "SELECT feedbackID, name, email, rating, review, image, suggestion, nps
            FROM feedback 
            ORDER BY feedbackID Desc";
    $queryResult = $dbConn->query($sql);
    
    // Check for and handle query failure
    if($queryResult === false) {
        echo "<p>Query failed: ".$dbConn->error."</p>n";
        exit;
    }
    
    // Otherwise fetch all the rows returned by the query one by one
    else {
        if ($queryResult->num_rows > 0) {
            while ($rowObj = $queryResult->fetch_object()) {
                echo "<tr>
                      <td>{$rowObj->feedbackID}</td>
                      <td>{$rowObj->name}</td>
                      <td>{$rowObj->email}</td>
                      <td>{$rowObj->rating}</td>
                      <td>{$rowObj->review}</td>
                      <td><img width='350px' height='200px' src='data:image;base64,{$rowObj->image}'/></td>
                      <td>{$rowObj->suggestion}</td>
                      <td>{$rowObj->nps}</td>
                      <td>
                      <button type='button' class='btn btn-danger' data-bs-toggle='modal' data-bs-target='#deleteModal' name='Delete' id='delete'>
                      <i class='fa fa-trash'></i> Delete</button>
                       <!-- Modal --->
                        <div class='modal fade' id='#deleteModal' tabindex='-1' aria-labelledby='deleteModalLabel' aria-hidden='true'>
                            <div class='modal-dialog'>
                                <div class='modal-content'>
                                    <div class='modal-header'>
                                        <h5 class='modal-title' id='deleteModalLabel'>Delete Confirmation</h5>
                                        <button type='button' class='btn-close' data-bs-dismiss='modal' aria-label='Close'></button>
                                    </div>
                                    <div class='modal-body'>
                                        Do you really want to delete this feedback?
                                    </div>
                                    <div class='modal-footer'>
                                        <button type='button' class='btn btn-secondary' data-bs-dismiss='modal'>No</button>
                                        <button type='button' class='btn btn-danger' href=delete.php?id={$rowObj->feedbackID} >Delete</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                      </td>
                      </tr>
        
                  ";

        }

    }
}
?>


    </tbody>
</table>
</div>

The delete button is not responding to execute the delete row command. Before adding modal I have the following code for the delete button, it worked fine but when I added modal it’s not responding:

<td><a class='btn btn-danger' href=delete.php?id={$rowObj->feedbackID} style='vertical-align:middle' id='delete'>Delete</a></td>

Hope I gave the enough info to solve the issue, TIA

Retrieve of promise from input file

I have an HTML file with the following code:

<input type="File" id="myFile" name="filename" onchange="loadFile(this.files[0])">

And a javascript file with the following code:

const fileInput = document.getElementById('myFile');
    fileInput.onchange = () => {
      var allFolders = fileInput.files[0].text();
      console.log(allFolders);
    }

When I open my console log, I receive the message:

Promise { <state>: "pending" }
​
<state>: "fulfilled"
​
<value>: "{'1' : { '2' : { '3' : { 'a': {}, 'b' : {}, 'c' : {}}}}};"

I want to console log ONLY the value so that my console log returns

"{'1' : { '2' : { '3' : { 'a': {}, 'b' : {}, 'c' : {}}}}};"

but I am not sure how to retrieve it, given the structure of the code I have written. Does anyone know, using the simple code I already have functioning, what to add to make console.log(allFolders) return the value of the promise?

how to send jwt token correctly

In my angular application I am trying to send a jwt token as a header in order to authorize my app for requests. But I am getting an error 500 because I am sending the jwt token in a wrong format, this is how I am sending right now:

Bearer {"id_token":"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTY1MDMxMTg0MH0.zWxESmFkM_nE8LEqIfFwSb-nEG593qaYnS1IFjd9qdYbOZJmMSXirfW3S68lQ0PBJcNop-OGtB6JJjtNJprDIQ"}

What I want is the following:

Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTY1MDMxMTg0MH0.zWxESmFkM_nE8LEqIfFwSb-nEG593qaYnS1IFjd9qdYbOZJmMSXirfW3S68lQ0PBJcNop-OGtB6JJjtNJprDIQ

I tried the following but I am getting an undefined can not read property of trim error:

token.split(" ")[1].trim()

could someone help me out and tell me what I am doing wrong? This is my interceptor where I am trying to send the header:

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor() {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (!request.url || (request.url.startsWith('http') && !(environment.rootUrl && request.url.startsWith(environment.rootUrl)))) {
      return next.handle(request);
    }
    const token =
      localStorage.getItem('token') ||
      sessionStorage.getItem('token');

    if (token) {
      console.log(token)
      request = request.clone({
        setHeaders: {
          Authorization: 'Bearer ' + token.split(" ")[1].trim()
        },
      });

    }
    return next.handle(request);
  }
}

Yelp API Request returning as “undefined”

I am making an API call to the yelp-fusion. However, when I try to log this result, the log shows as undefined. I assume this is due to something regarding promises or async functions. Note: I need to keep this in a function as I intend to export this function to other files.

const searchRequest = {
  term:'cafe',
  location: 'san francisco, ca'
};

const client = yelp.client(apiKey);

function businessSearch(search){
client.search(search).then(response => {
    return response
  }).catch(e => {
    console.log(e);
  });
}

console.log(businessSearch(searchRequest))

Cannot find module ‘semver/functions/cmp’ React Native CLI

I have been developing the application in Expo. I’ve had to revert to using React Native CLI as I need access to a package Expo doesn’t support. My project didn’t run so I’ve built a new project by copying across all .js files and then yarn installing all the packages I need.

It’s failing to build with the following error.
Can anyone help? I have no idea what’s going on, I’m new to react native and the environment.


error: index.js: [BABEL] C:UsersowenjOneDriveDesktopFYPGlucoseProjectFYPindex.js: Cannot find module 'semver/functions/cmp'
Require stack:
- C:UsersowenjOneDriveDesktopFYPGlucoseProjectFYPnode_modulescore-js-compathelpers.js
- C:UsersowenjOneDriveDesktopFYPGlucoseProjectFYPnode_modulescore-js-compatget-modules-list-for-target-version.js
- C:UsersowenjOneDriveDesktopFYPGlucoseProjectFYPnode_modulesbabel-plugin-polyfill-corejs3core-js-compatget-modules-list-for-target-version.js
- C:UsersowenjOneDriveDesktopFYPGlucoseProjectFYPnode_modulesbabel-plugin-polyfill-corejs3libindex.js
- C:UsersowenjOneDriveDesktopFYPGlucoseProjectFYPnode_modules@babelplugin-transform-runtimelibindex.js
- C:UsersowenjOneDriveDesktopFYPGlucoseProjectFYPnode_modulesmetro-react-native-babel-presetsrcconfigsmain.js
- C:UsersowenjOneDriveDesktopFYPGlucoseProjectFYPnode_modulesmetro-react-native-babel-presetsrcindex.js
- C:[email protected]
- C:[email protected]
- C:[email protected]
- C:[email protected]
- C:Usersowenjnode_modulesmetro-transform-workersrcindex.js
- C:Usersowenjnode_modulesmetrosrcDeltaBundlerWorker.js
- C:Usersowenjnode_modulesjest-workerbuildworkersprocessChild.js (While processing: "C:\Users\owenj\OneDrive\Desktop\FYP\GlucoseProject\FYP\node_modules\metro-react-native-babel-preset\src\index.js")```

SAPUI5 Tree Table extension

I am using this SAPUI5 tree table and would like to change the arrow icon indent and table row background colour for each level of the tree.

What I am trying to achieve – each expanded tree level should have a different shade of grey and the indent of (level * 5px). At the moment the indent increases by 17px.

I would like to know how to achieve it through CSS and through UI5 control extension.

I know that for one a generic table row I could use

tr>td>div>span.sapUiTableTreeIcon {
margin-left:5px !important;
background-color: #F8F8F8;
}

But how to make it dynamic that each level indent will increase by (level * 5) pixels?

Also I would like to achieve the same by extending the UI control, but can’t find in the library the exact place that generates the (level * 17px ) indent.

Style screenshot

I had a look at the library file sap.ui.table.TableRenderer-dbg.js and I can see that the icon row gets generated by the following function:

TableRenderer.renderTableCellControl = function(rm, oTable, oCell, bIsFirstColumn) {
        if (bIsFirstColumn && TableUtils.Grouping.isInTreeMode(oTable)) {
            var oRow = oCell.getParent();
            rm.openStart("span", oRow.getId() + "-treeicon");
            rm.class("sapUiTableTreeIcon");
            rm.attr("tabindex", "-1");
            oTable._getAccRenderExtension().writeAriaAttributesFor(rm, oTable, "TREEICON", {row: oRow});
            rm.openEnd();
            rm.close("span");
        }
        rm.renderControl(oCell);
    };

But I can’t see where the margin-left get’s generated, it doesn’t seem to be in any of the CSS classes mentioned above. Any idea where it comes from?

querySelectorAll only gives output for one div after forEach() loop

Recently, I have been trying to create a wordle game but with 8 letters, and it has been going well, though, when I input my answer into the div boxes, only the first div gets a response when I click the big “CHECK” button. I am attempting to use a forEach() loop to solve this problem but I am still only getting one div to get an output… could someone please help me? Also, I want it to work for the multiple divs in the grid, just for clarification.

Full code: https://code.sololearn.com/WX59M6HHngc5

Here is my JS code:

const pText = document.querySelector("#p123").innerText.toUpperCase()
const button = document.querySelector("#button123")

Array.from(document.querySelectorAll(".amot")).forEach(function(element) {

button.addEventListener("click", () => {
  const text = document.querySelector(".amot").textContent.toUpperCase()

  //don't check if there are numbers/non letters and text length < 8
  if (text.match(/d/gi) || text.length < 1 || text.match(/[^a-z]/gi)) {
    document.querySelector(".amot").innerText = text
    return
  }

  document.querySelector(".amot").innerHTML = ""
  text.split("").forEach((letter, i) => {
    if (pText.includes(letter) && pText[i] === letter) {
      document.querySelector(".amot").innerHTML += `<span style="color: lime">${letter}</span>`
    } else if (pText.includes(letter)){
      document.querySelector(".amot").innerHTML += `<span style="color: orange">${letter}</span>`
    } else {
      document.querySelector(".amot").innerHTML += `<span style="color: lightgrey">${letter}</span>`
    }
  })
})

//blur the div if text is longer than 8 letters or key = "space"
document.querySelector(".amot").addEventListener("keydown", (e) => {
  if (document.querySelector(".amot").innerText.length > 0 || e.keyCode == 32) {
    document.querySelector(".amot").blur()
  }
})

//clear on focus
document.querySelector(".amot").addEventListener("focus", () => {
  document.querySelector(".amot").innerHTML = ""
})},

Here is some of my HTML code (The rest can be found at the link at the bottom):

<p id = "p123">ABsOLUTE</p>
<div id = "div123" contenteditable="true" style="border: 5px solid; padding: 5px; font-size: 22px; font-weight: bold; text-transform: uppercase;" spellcheck="false"></div>
<button id = "button123">check</button>
<div id = "amoo">
<div class="container" style = "position:relative; left:825px; top:-400px;" id = "testu">



    <div oninput = "inputFunc()" tabindex = "1" class = "amot" onkeypress="return (this.innerText.length <= 0)" contenteditable = "true" id = "amo1"></div>
    <div oninput = "inputFunc()" tabindex = "2" class = "amot" onkeypress="return (this.innerText.length <= 0)" contenteditable = "true" id = "amo2"></div>
    <div oninput = "inputFunc()" tabindex = "3" class = "amot" onkeypress="return (this.innerText.length <= 0)" contenteditable = "true" id = "amo3"></div>
    <div oninput = "inputFunc()" class = "amot" onkeypress="return (this.innerText.length <= 0)" contenteditable = "true" id = "amo4"></div>
    <div oninput = "inputFunc()" class = "amot" onkeypress="return (this.innerText.length <= 0)" contenteditable = "true" id = "amo5"></div>
    <div oninput = "inputFunc()" class = "amot" onkeypress="return (this.innerText.length <= 0)" contenteditable = "true" id = "amo6"></div>
    <div oninput = "inputFunc()" class = "amot" onkeypress="return (this.innerText.length <= 0)" contenteditable = "true" id = "amo7"></div>
    <div class = "amot" onkeypress="return (this.innerText.length <= 0)" contenteditable = "true" id = "amo8"></div>
    <div class = "amot" onkeypress="return (this.innerText.length <= 0)" contenteditable = "true" id = "amo9"></div>
    <div class = "amot" onkeypress="return (this.innerText.length <= 0)" contenteditable = "true" id = "amo10"></div>
    <div class = "amot" onkeypress="return (this.innerText.length <= 0)" contenteditable = "true" id = "amo11"></div>
    <div class = "amot" onkeypress="return (this.innerText.length <= 0)" contenteditable = "true" id = "amo12"></div>
    
</div>

Here is my full code: https://code.sololearn.com/WX59M6HHngc5
Please help me! Thank you in advance…