Extract fetched data using map method

I am trying to fetching data from newsapi website. It gives me data as array like object format.

enter image description here

Now, my goal is to iterate this data and display my newsItem component. Here is my code below.

export class News extends Component {
    constructor(){
        super()
        this.state = {
            articles: this.articles
        }
    }
    componentDidMount(){
        fetch(`https://newsapi.org/v2/top-headlines?country=us&apiKey=d21fe13361b94006b816f98a7c005003`)
        .then(res =>res.json())
        .then(data => this.setState({articles:data.articles}))
    }
  render() {
    return <div className='container my-3'>
        <h1 className='my-3'>NewsDonkey - Top Headlines</h1>
        <div className="row">
                {this.state.articles.map(element=> console.log(element))}
            <div className="col-md-4">
                <NewsItem/>
            </div>
        </div>
    </div>;
  }
}

export default News;

but, browser shows can’t read properties of undefined. Here is the error image.
enter image description here

Now, you may say that data may be in object format that’s why map method is not working. I tried same coding in JS: articles.map(element=> console.log(element)) it extracted data perfectly. Please help me if you find any error in my coding.

How can I create a function that will remove a specific item from an array/ul? [closed]

I’m making a mini program to allow me to create a list of items (e.g Coffee, milk, eggs) by typing the item into a bar, pressing a button and then adding the item to an unordered list.

I have managed to create a function that adds an item to the list, but now I want to create a function that removes a specific item that has been added to the list.

Anyone have any ideas? Much appreciated!
Thanks

Is there any way to delete useless functions in JS libraries?

I’m building a project in javascript, using paper.js in some features.
Most of my project is built in vanilla Javascript, just some minimum but important features are built with paper.js

The problem is that the library (.min library) is 200kb.
The normal library is 300kb, I was wondering if there is an automatic way to see which functions are being used in the main paper.js library, in order to delete the useless functions.
If there is no program or automatic way to do this, maybe some advice of how to do it manually, or which tools you recommend for me and my team in order to delete useless functions, then minify the file and run it smaller.

Thank you all guys, I did not added any specific code because I want this anwser to be global.

Greetings

Read a graphql richtext

first of all, sorry for eventualy bad english writte =)

Ok, my trouble is about read a richtext maked in graphcms and bring to my jsx.

I can’t read a list-numered array. Tried a case type: numbered-list, so it’s work, but can’t map a array to show my list, lets code:

  • class='list-decimal' is tailwind
  • here:, bring to me undefined five times

And I want some thing like this:

  1. numeber one
  2. number two
  3. number three
    1. number one in three
    2. number two in three
  4. number four
  5. number five
const getContentFragment = (index, text, obj, type) => {
        let modifiedText = text;
        
          switch (type) {
            case 'numbered-list':
            return <p key={index} class="list-decimal">
                      <ol>
                        {modifiedText.map((item, i) => 
                          <React.Fragment key={i}>
                            <li>
                              {item}
                              {console.log('here:', item)}                                                </li>                  
                          </React.Fragment>
                          )
                        }
                      </ol>
                    </p>;
          }
        }

array being pushed data but empty when logging [duplicate]

Hey all I currently have the forEach method below in an array

let distances = []

            markers.forEach((el) => {
              new google.maps.DirectionsService().route({
                origin: address,
                destination: el.address,
                travelMode: google.maps.TravelMode.DRIVING
              })
                .then((response) => {
                  distances.push(response) 
                  // For each route, display summary information.
                })
                .catch((e) => console.log('Directions request failed due to ' + status))

              console.log(distances)
            })

does anyone know why I cant see the items after they are all pushed ?

apidata.map is not a function : ReactJS

Can someone please tell me why i am getting this error . I tried fixing it all day, but I could not fix it. So at last i had to come at stackoverflow

This is my code : App.js

import "./App.css";

function App() {
  const [inputvalue, setInputvalue] = useState(" ");
  const [apidata, setApidata] = useState([]);
  const [finalpoint, setFinalpoint] = useState("");
  useEffect(() => {
    fetch(
      `https://weatherapi-com.p.rapidapi.com/forecast.json?q=+${inputvalue}&days=3`,
      {
        method: "GET",
        headers: {
          "x-rapidapi-host": "weatherapi-com.p.rapidapi.com",
          "x-rapidapi-key":
            "7f89bf16ebmsh9dff0f23f963d34p190691jsn264543e18108",
        },
      }
    )
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        setApidata(data);
      })
      .catch((err) => {
        console.error(err);
      });
  }, [finalpoint]);

  const onchangeinput = (e) => {
    setInputvalue(e.target.value);
  };

  const onsubmithandler = (e) => {
    e.preventDefault();
    setFinalpoint(inputvalue); 
  };

  return (
    <div className="App">
      <div className="main">
        <h2>Welcome To weather App </h2>
      </div>

      <form onSubmit={onsubmithandler}>
        <input type="text" value={inputvalue} onChange={onchangeinput} />
        <button type="submit">Search</button>
      </form>
      {apidata.map((data, i) => {
        return <h1>{data.current.feelslike_c}</h1>;
      })}
    </div>
    //Map
  );
}

export default App;

This is the error I am getting :
enter image description here

Error: One of the `NSLocation*UsageDescription` keys must be present in Info.plist to be able to use geolocation

When I want to test my app with Expo Go on iOS I get this error:

[Unhandled promise rejection: Error: One of the `NSLocation*UsageDescription` keys must be present in Info.plist to be able to use geolocation.]

Stack trace:
  node_modulesreact-nativeLibrariesBatchedBridgeNativeModules.js:104:50 in promiseMethodWrapper
  node_modulesexpo-modules-corebuildNativeModulesProxy.native.js:15:23 in moduleName.methodInfo.name

I added that configuration to info.plist, rebuilt the project, but I get the same error, I also reinstalled node packages, but it didn’t change anything.

package.json

    "dependencies": {
        "@expo/vector-icons": "^12.0.0",
        "expo": "~43.0.2",
        "expo-location": "~13.0.4",
        "expo-status-bar": "~1.1.0",
        "expo-task-manager": "~10.0.3",
        "react": "17.0.1",
        "react-dom": "17.0.1",
        "react-native": "0.64.3",
        "react-native-paper": "4.9.2",
        "react-native-web": "0.17.1",
        "expo-splash-screen": "~0.13.5",
        "expo-updates": "~0.10.13",
        "react-native-gesture-handler": "~1.10.2",
        "react-native-reanimated": "~2.2.0",
        "react-native-safe-area-context": "3.3.2",
        "react-native-screens": "~3.8.0"
      },
      "devDependencies": {
        "@babel/core": "^7.12.9"
      }

My js code

  const { status } = await Location.requestForegroundPermissionsAsync();
    if (status === "granted") {
      const background = await Location.requestBackgroundPermissionsAsync();
      if (background.status === "granted") {
        await Location.startLocationUpdatesAsync(TASK_FETCH_LOCATION, {
          activityType: Location.LocationActivityType.BestForNavigation,
          showsBackgroundLocationIndicator: true,
          accuracy: Location.Accuracy.BestForNavigation,
          deferredUpdatesInterval: 3000,
          deferredUpdatesDistance: 50,
          showsBackgroundLocationIndicator: true,
        }).then(() => {
          Alert.alert("Turn on", null, [
            { text: "OK", onPress: () => console.log("listening gps") },
          ]);
        });
      }
    }

app.json

   "ios": {
      "supportsTablet": true,
      "infoPlist": {
        "UIBackgroundModes": [
          "location",
          "fetch"
        ],
        "NSLocationAlwaysAndWhenInUseUsageDescription": "Allows App to use location services in the foreground and background.",
        "NSFaceIDUsageDescription": "Allows App to use Face ID for a simpler sign in."
      }
    }

It is possible to use a function of a child class in variable defined with parent class?

i am playing a bit with some code snippets and i am asking if its possible to use a function that was defined in a child class (with extends), to use in a variable that was created with the parent class?

Here is my code snippet:

class Workshop {
constructor(teacher) {
    this.teacher = teacher;
}
ask(question) {
    console.log(this.teacher, question);
}
}

class AnotherWorkshop extends Workshop {
    speakUp(msg) {
        console.log(msg);
    }
}

var shallowJS = new Workshop("Toby");

shallowJS.ask("you are there?");
shallowJS.speakUp("still there?");

Is there anyway, that i can access the function speakUp from the child class AnotherWorkshop with shallowJS.xxxx ? (and i dont mean the way to create a new variable of shallowJS)

Thanks a lot for help 🙂

Multiple awaits inside an async function

New to javascript, coming from a c# world. I keep getting the following error message in node

SyntaxError: await is only valid in async functions and the top level bodies of modules

for the following code:

exports.sendNotification = functions.https.onRequest(
  async (request, result) => {

    const docs = await firebase
      .firestore()
      .collection("Users")
      .select("userId", "tokenId")
      .get();

    docs.forEach((doc) => {
        const moreDocData = await firebase
        .firestore()
        .collection(doc.data()["userId"])
        .get();

    });

        //doesn't work here either
        //const moreDocData = await firebase.firestore().collection(doc.data()["userId"]).get();

    return result.send("Ok");
  }
);

What I am essentially trying to do is await the fetching of the docs, and then I want to fetch more docs based on the userID of the data that I got. I can’t seem to get the second await correctly regardless of it’s inside the foreach or outside of it. What am I doing wrong?

How to launch ajax function based on a condition in a javascript function

I’m trying to launch an ajax call based on a condition (folder not empty) .

The result of my condition is working fine in php file check_file.php

Here is my check_file.php how it looks like

<?php

if (!empty($_POST["folder"])) 
{
$dir = $_POST['folder'];
$files = array_diff(scandir($dir), array('.', '..'));
$result;

if (!is_dir_empty($dir) && trim(substr( json_encode($files), 6, 2 )) == 'ok'  )  
{ 
$result = 0;  
}
else  {$result = 1;}

echo $result;
unlink($dir.'/'.trim($files[2])  )  ; 
}

function is_dir_empty($dir) {
if (!is_readable($dir)) return null; 
return (count(scandir($dir)) == 2);
}
?> 

In my JavaScript script this is how it looks like

function downloadExcel() {
// Mu folder path 
var folder="D:/output";
if (result.isConfirmed) {
               $.ajax({
                    type: 'POST',
                    url: 'check_file.php',
                    data: {
                        folder: folder
                    },
                    cache: false,
                    success: function(result){
                        if(result==0)
                        {
                            Swal.fire(
                                    'Execution  success , please check your email '
                            );
                        }
                        else
                        {
                            Swal.fire(
                                'Execution  en cours   '
                            );  
                        }
                        
                },
            error: function(result){

               console.log("Error request Ajax");
            } 
            });
            
            refresh();

        } else 
            result.dismiss === Swal.DismissReason.cancel
        }

I’m new to javascript , how could i test if folder is not empty launch the $.Ajax call

I can’t pass arguments to the calling function

I am failing to pass arguments to the calling function.

Specifically, I have a table where when I click on the title I have to open a form where the value of the arguments passed must be copied into the various fields of it. To do this, I call through href (as you can see from the code) the function with the parameters passed.

I get the following error:

Uncaught SyntaxError: missing ) after argument list

Object.entries(results).forEach(item => {
  item = item[1];
  let child = document.createElement("tr");
  child.innerHTML = `
                        <td>${item.number}</td>
                        <td><a href="javascript:showFrag(${item.id},${item.number},${item.type});">${item.type}</a></td>`;
  document.querySelector('#my-table').appendChild(child);
})

function showFrag(id, number, type) {
  return id, number, type;
}

function onLoad() {
  showFrag(id, number, type);
  var id = document.getElementById('id');
  var number = document.getElementById('number');
  var type = document.getElementById('type');
  id.value = id;
  numbr.value = number;
  type.value = type;
}
onLoad();
<div class="split left">
  <div class="centered">

    <table id="my-table" width="90%">
      <tr>
        <th>Number</th>
        <th>Type</th>

      </tr>

    </table>

    <br><br>

  </div>
</div>

<div class="split right">
  <div class="centered"> <br>
    <div class="container">
      <form method="post" id="save" action="javascript:myFunction()" onload="onLoad()">

        <div class="field">
          <label for="id">ID :</label>
          <input type="number" id="id" name="id" />
        </div>

        <div class="field">
          <label for="number">Number:</label>
          <input type="number" id="number" name="number" />
        </div>
        <div class="field">
          <label for="type">Type:</label>
          <select name="type" id="type" form="typeform">
            <option value="Title">Title</option>
            <option value="Text">Text</option>
            <option value="Video">Video</option>
          </select>
        </div>

        <div class="button">
          <button type="submit" class="full">Save modifiche</button>

        </div>
      </form>
    </div>
  </div>
</div>

myFunction() is not present because it has yet to be done, I am only interested in passing for now the value of the parameters passed in the various fields of the form .

Group array of object base on one unique property?

how to turn below array of object

const items = [
    { id: 1, name: 'a' },
    { id: 2, name: 'b' },
    { id: 3, name: 'c' },
    { id: 1, name: 'd' },
    { id: 3, name: 'f' },
    { id: 1, name: 'a' },
    { id: 3, name: 'c' },
  ];

into

 const result = [
   { id: 1, names: ['a', 'd']},
   { id: 2, names: ['b']},
   { id: 3, names: ['c', 'f']}
  ] 
  

without using external like lodash?

Why is ‘undefined’ returned when comparing an function argument to a string from a function?

While there aren’t errors in my code, hopefully there isn’t, whatever I try to do something, or try to understand based on the way I’ve been taught so far, I can’t really proceed any further. Let me explain by showing my code.

function cpuPlay(){
    let numberGen = Math.floor(Math.random() * 3)

  if (numberGen === 0){
    return 'rock'
  }
  if (numberGen === 1){
    return 'paper'
  }
  if (numberGen === 2){
    return 'scissors'
  }
}
// cpuPlay()

function rps(playersChoice){
  if(playersChoice == 'paper' && cpuPlay() == 'rock'){
    console.log('rock')
  } else if (playersChoice == 'paper' && cpuPlay() == 'paper'){
    console.log('paper')
  } else if (playersChoice == 'paper' &&  cpuPlay() == 'scissors'){
    console.log('scissors');
  }
}
rps('paper')

I created cpuPlay to call either rock, paper, or scissors, whenever a random number between 0-2 is called, this function works properly, but rps() is the function that I can’t seem to build properly after 3 days of doing this. No matter how I build this, it seems I keep on getting one of four answers when I call rps(), the answers I get are either ‘rock’,’paper’,’scissors’,’undefined’. Before I thought it was because I used, .toLowerCase() on playerChoice but either way, this function has been giving the same results, if you keep on running rps(‘paper’), it’s eventually show. I’m not sure how I should go any further with this problem, or maybe I’m not supposed to be able to compare, I don’t even know anymore.

How to iterate over a range and an array of data and set the iterated array values until there’s no data using GAS?

This may seem simple to you, but well….here I am.

The code below sets the last value to all cells in the rangeList and I’d like to know where the flaw is:

const rngs = ["A10", "F10", "J10", "A12", "F12", "J12"];
const rangeList = sheetVendSobEnc.getRangeList(rngs).getRanges();
let coresPartes = ["Alca", "Mangas"]//Splits the value into a 1D array
  for (let a = 0; a < rangeList.length; a++) {
    for (let n = 0; n < coresPartes.length; n++) {
      if(coresPartes[n] != ''){
      rangeList[a].setValue(coresPartes[n])
      }
    }
  }

Thank you in advance!

how to add variable link in html

i have a remote php file located on a server

https://webserver.com/file.php

and i have several images in html file on another server that are linked through

<div class="apps">
    <a href = "file.php?type=1"><img src="https://anysite.com/image.jpeg" alt="image" border="0"></a></br>
    logo
</div>

i want to replace the main link with a variable and add it to my images.

should appear link the following:

<div class="apps">
    <a href = "$variable?type=1"><img src="https://anysite.com/image.jpeg" alt="image" border="0"></a></br>
    logo
</div>

Anyone can help please?