empty useState on request React

I am using a button to perform a fetch request, when I do it and try to set the response in useState it always stays empty but if I click the button again now it sends me the information correctly.

This is my code:


  const fetchUsers = async (page, limit = perPage, search = searchBox, type) => {

    if (type === 'all') {
      limit = 100000
    } else {
      setLoading(true);
    }

    const dataOnLs = localStorage.getItem('cmtjs')

    const config = {
      headers: {
          "Content-Type": "application/json",
          apiKey: dataOnLs
      } ,
      params: {
          limit,
          page, 
          search
        }            
  }
    const response = await axiosClient(`/products`, config)
    console.log(response.data.products.docs); // DATA OK
    if (type === 'all') {
      setDataToXLS(response.data.products.docs); // **EMPTY**
    } else {
      setData(response.data.products.docs); // DATA OK
      setTotalRows(response.data.products.totalDocs);
      setLoading(false);
    }
  };

I don’t understand why it doesn’t set my useState (setDataToXLS) with the data on the first click and I have to click twice to get the data correctly

Open layers Angular how to adjust opacity with a slider

I have a map thats generated on the components init that runs a method called makeMap() that creates a map that looks like follows

makeMap() {

  var osm = new TileLayer({
    source: new OSM(),
  });

  ...

  this.map = new Map({
    layers: [osm, wktLayer, this.tiles],
    target: 'ol-map',
    view: new View({
      center: proj.fromLonLat(coordinates),
      zoom: 9,
      minZoom: 8.75,
    }),
  });
}

I am trying to add a slider on the front end that can adjust the opacity of the layer “this.tiles”. I have the following html for a slider. for testing right now im trying to adjust it as follows.

  setOpacity() {
    this.tiles.setOpacity(0);
    this.map.render()
  }

the issue is when I try to call the method after the map is created it doesnt update the layer only if I call it before its made. Im trying to connect it to a slider as follows

      <input
        id="opacity-input"
        type="range"
        min="0"
        max="1"
        step="0.01"
        value="1"
      />

How can I update the opacity of the layer when the slider changes value? I am new to angular and openlayers so im not sure how to create this functionality.

useRef value not persisting

I am building a weather app where i have an index page which displays a bunch of cards for each hour. I have a value (whether it is AM or PM) which i am storing in a useref and passing it to child component. When some condition is met an onChange function is called from the child (this function exist in the parent)and changes the value of the useref but the value is not changing in the child. The bunch of cards are displayed by mapping through them so i am expecting if the useref value is changed in the parent the next card would get the changed value but this is not happening. Am i using useref wrong?
index.js

import type { NextPage } from 'next'
import WeatherCard from '../components/WeatherCard'
import { motion } from 'framer-motion'
import { useEffect, useRef, useState } from 'react'
import { PropsType } from '../types'

const Home: NextPage<PropsType> = (props) => {

  const [time,setTime]=useState(new Date());
  const timeFormatRef=React.useRef(new Date().toLocaleString('en-US', 
                    {hour: 'numeric', hour12: true }).split(' ')[1]) as any;
  
  const onTimeFormatChange=()=>{
    if(timeFormatRef.current==='AM')  
      timeFormatRef.current='PM' 
    else 
      timeFormatRef.current='AM';
  }
  
  return (
    <div className=>
      <main>
         {determineWeatherCardsArr().map((el,index)=>{
           return <motion.div>
                    <WeatherCard key={index} weather={el.weather} 
                                temp={el.temp} index={index} 
                                time={time} ref={timeFormatRef} 
                               onTimeFormatChange= {onTimeFormatChange}/>
                   </motion.div>})
      </main>
    </div>
  )
}

export default Home

WeatherCard.js

import Image from "next/image";

const WeatherCard:React.forwardref=(props,ref)=>{

    const determineHour=(time:Date):string=>{
        
        let amPmTimeArr=time.toLocaleString('en-US', 
                   { hour: 'numeric', hour12: true }).split(' ');
        let hour
        [hour]=[...amPmTimeArr]
        
        if(+hour+props.index>=12){
            hour=(+hour+props.index)%12;
        
            if(+hour===0){
               props.onTimeFormatChange();//changing the useref here 
               
            }
            
            return hour+ref.current;
        }
        else{
            hour=+hour+props.index
            return hour+ref.current;
        }
         
    }

    let cardTitle=determineHour(props.time)
    return(
        <div className="">
            <h3 className="">{cardTitle}</h3>
        </div>
    )
}

Vanilla javascript – binding an evevntlistener (‘click’) to a dynamic element

Lets say you have a create button that dynamically creates a

element and a element named play.
The play button has an eventlistener(“click”) that has a variable named timer that equals
set interval which runs a function named start timer that displays a time elapsed within the innerHTML of the

that was created.

QUESTION: Since there can be multiple timer buttons created, how can you bind the play button clicked with the

that it was created with?

How do I use newly installed modules in React when they do not appear in the package.json “dependencies” list?

I am quite new at working with React so this maybe a basic question. I installed several modules and when I check in the terminal using

npm ls --depth=0

I see they are all present. However, when I open my React app and go to “dependencies” in the package.json file a number of the listed modules are missing.

Is this something I need to add manually in order to use the new packages? Or if I import them directly into a .js file will they work as intended?

vue reset the pushed data

what I want to do may be simple but what I don’t understand is,
When I click on any of the buttons, I push the new number. but what I want is, I want every data pushed to be initialized.

<div>
    output : {{hello}},
    <button @click="addItem(5)"></button>
    <button @click="addItem(65)"></button>
</div>
<script>
export default {
  data() {
    return {
      hello: [1, 9, 15, 7, 9]
    }
  },
  methods: {
    addItem(newnumber) {
      this.hello.push(newnumber)
    }
  }
}
</script>

how to fetch data through a json file online through laravel?

I’m trying to fetch data from a json file online “https://jsonplaceholder.typicode.com/posts” and for some reason I get this error “cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https ://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://jsonplaceholder.typicode.com/posts” and I don’t know why, can anyone understand this error?

PostController.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use IlluminateSupportFacadesHttp;

class PostController extends Controller
{
    public function index(){
        // call apis

        $posts = Http::get("https://jsonplaceholder.typicode.com/posts");
    
        return $posts;
    }
}

web.php

<?php

use IlluminateSupportFacadesRoute;
use AppHttpControllersPostController;

Route::get('/', [AppHttpControllerswebHomeController::class, 'home']);
Route::get("/posts", [PostController::class, "index"]);

How to select a neighbouring node from within an arrow function?

The JS and HTML at this jsfiddle and shown below is part of a settings menu, which is a list of URLs and an ‘x’ button next to each. This is part of my fork of this RSS app, so not something I’m building from scratch. In practice it looks like:

x foo.com
x bar.com/rss
x baz.com/feed

The renderSettings() function injects data from a JSON array into the <template id="settings-feed-item"> div, which is why nothing shows up in the JSFiddle preview. That function also adds the onclick functionality to every instance of the #remove div.

Aside from other code I’ve trimmed out for brevity, I want to apply CSS styling to a #feedurl when the #remove next to it is clicked.

The problem I’m having is that I can’t figure out how to select the #feedurl. I’ve tried this. and the closest() method but I can’t select it. Everything I’ve tried so far gets me TypeError: undefined is not an object in the console. What am I missing?

HTML

<section id="feedsection">
  <ul id="feeds">
    <template id="settings-feed-item">
      <li>
        <a id="remove">x&emsp;</a><span id="feedurl"></span><a></a>
      </li>
    </template>
  </ul>
</section>

JS

// RENDER SETTINGS MENU
function renderSettings() {
  keywords.value = state.keywords;
  newsFeeds.innerHTML = '';
  state.feeds.forEach(f => {
    const el = document.importNode(feedItem.content, true).querySelector('li');
    el.querySelector('span').innerText = simplifyLink(f.url);
    // ...
    // onclick `#remove`
    el.querySelectorAll('a')[0].onclick = () => {
      // SELECT URL NEXT TO CLICKED X
    };
    // ...
  });
}

Why is that when using Typescript in VSCode, once it accepts split method for a string array, in other examples it does not?

I have two different TS files opened in VSCode and learning and using string manipulation methods.

Right now, I can’t figure whether VSCode is screwing with me or I made a mistake, but I will copy/paste the code of the two files for comparison. Highlighting which one shows up as not ok.

The first piece of code is where it shows badly(in Typescript), it’s the last line:

// - Create an empty list which will contain names (strings)
let myList:string[] = [];
// - Print out the number of elements in the list
console.log(myList.length);
// - Add "William" to the list
myList.push("William");
// - Print out whether the list is empty or not
console.log(myList.length);
// - Add "John" to the list
myList.push("John");
// - Add "Amanda" to the list
myList.push("Amanda");
// - Print out the number of elements in the list
console.log(myList.length);
// - Print out the 3rd element
console.log(myList[2]);
myList.forEach(v => console.log(v));
for (let i=0;i<myList.length;i++){
   console.log((i+1).toString()+". "+myList[i]);
}
// - Remove the 2nd element
console.log(typeof(myList));
console.log(myList);

let newList:string[] = myList.split(” “);

The second piece of code where EVERYTHING IS OK< NO ERROR, but I am using the same split method in syntax with an array of strings.

let url: string = 'https//www.reddit.com/r/nevertellmethebots';

//Megoldas 3
console.log(url.replace("//","://").replace('bots','odds'));

//Megoldas 1
let strArr: string[] = url.split('//');
strArr.push('://');
let temp = strArr[2];
strArr[2] = strArr[1];
strArr[1] = temp;
console.log(strArr.join('').replace('bots','odds'));

//Megoldas 2
let strArr2: string[] = url.split('');
strArr2[5] = ':/';
console.log(strArr2.join('').replace('bots','odds'));

What can be the problem? Can you copy/paste the code if you use VSCode to confirm, please? What did I type wrong?

Why isn’t my GitHub secret being recognized by my Firebase-deployed React app?

In my React app, I have an API key bound to a variable:

import React, { useState, useEffect } from 'react'
import WeatherCard from './WeatherCard';

export default function Weather() {
  const apiKey = process.env.REACT_APP_API_KEY;  // API KEY BOUND HERE
  const [forecastObj, setForecastObj] = useState({});
  console.log(apiKey) //DID IT BIND SUCCESSFULLY?

  useEffect(() => {
    fetch(`https://api.weatherapi.com/v1/forecast.json?key=${apiKey}&q=${zipCode}&days=3&aqi=no&alerts=no`)
      .then(reply => reply.json())
      .then(
        json => {
          setForecastObj(json);
          setisLoading(false);
        })
  }, [apiKey])

// Setting "days" to the array containing daily forecasts
  const days = forecastObj.forecast.forecastday;
  
  return (
    <div className="container">
      {days.map((day, index) => {
        return(
          <WeatherCard
          key={index}
          day={day} 
          />
          )
        })}
    </div>
  )
}

Running npm start locally returns the API key in the console, and properly displays the app in-browser.

This is for a class, and my instructor is insisting the GitHub repo secret is all that’s needed for the key to be used by my code. I’ve set up both an Environment secret and repo secret containing the key (one after the other when the first didn’t work, I can’t remember which I tried first).

When I start a build Action in GitHub to deploy to Firebase it’ll complete successfully, and the page/app can be accessed, but will show a blank screen with an undefined return in console (from the console.log(apiKey); line), along with the error:

Uncaught TypeError: r.forecast is undefined  Weather.jsx:39:15
    u Weather.jsx:39
    React 8
    S scheduler.production.min.js:13
    T scheduler.production.min.js:14
    813 scheduler.production.min.js:14
    Webpack 12

Mozilla’s dev console also provides the error: GET https://api.weatherapi.com/v1/forecast.json?key=undefined&q=97232&days=3&aqi=no&alerts=no

This tells me that the API key isn’t being used, but when my instructor used the same setup (React app hosted to Firebase, secret in repo secrets) to render an app version label using the code:

Version: {process.env.REACT_APP_VERSION}

…it shows up.

So far I’ve tried setting up Firebase functions to hold the key, but half of the resources I found on the subject (I went down a bit of a rabbit hole) don’t seem to apply to a simple React app.

So what am I doing wrong?

Does fetching embeds through messages from msg.reference.messageID not work?

I am coding a discord bot, and I am trying to get the content of embeds through the command user replying to the message and using a prefix. When I try running the command, it says that fetchedMsg.embeds[0] isn’t a thing. Is there anything wrong with my code?

if (msg.reference) {
    const fetchedMsg = await msg.channel.messages.fetch(msg.reference.messageID)
    console.log(fetchedMsg)
    console.log(fetchedMsg.embeds[0])
}

The error is on the line console.log(fetchedMsg.embeds[0]), and looking at the log from the code before it includes embeds: [ [MessageEmbed] ],.

Access data inside an object inside array with map

i had an issue about how i can take a values inside this array:

Array [
  Object {
    "bairro": "pinheiro",
    "cep": 93042082,
    "id": "ujyB0pIocc7DxZpVYu3P",
    "logradouro": "av imperatiz leopoldina",
    "name": "arthur",
    "numero": 1860,
    "uf": "rs",
  },
  Object {
    "bairro": "Pinheiro",
    "cep": "93042082",
    "id": "xB1HxhiytOEt9Eey4weX",
    "logradouro": "Av imperatriz",
    "name": "Joyce",
    "numero": "1860",
    "uf": "Rs",
  },
]

below is my code with map, but the map don’t work correctly he don’t show a values accessing by dot i can access a values using [0] but this only work for one register and i have many.

const [users, setUsers] = useState([]);

  const usersCollectionRef = collection(db, "users");

  useEffect(() => {
    const getUsers = async () => {
      const data = await getDocs(usersCollectionRef);
      setUsers(data.docs.map((doc) => ({ ...doc.data([]), id: doc.id })));
    };
    getUsers([]);
  }, []);

return (

     {users.map((user) => {
        <Text>{user.name}</Text>;
     })}

)

How to prevent a JavaScript function being declared or defined more than once even though script is src’d more than once

I have a situation where a website developer can pull multiple instances of my script down, but I don’t want the code to execute more than once. The duplicate instances of the code are incidental, and not intentional by the developer. (something like this though not exactly https://www.quora.com/What-is-the-diamond-problem-in-programming?share=1)

Which of these approaches is best to prevent multiple src= JavaScripts that contain that code, from all executing it?

if (typeof myfunc === 'undefined') {
    myfunc = function() { // do it!!! }
    myfunc();
}

if (!myfunc) {
    myfunc = function() { // do it!!! }
    myfunc();
}

if (typeof window.myfunc === 'undefined') {
    window.myfunc = function() { // do it!!! }
    window.myfunc();
}

if (!myfunc) {
    var myfunc = function() { // do it!!! } // is myfunc even visible outside this scope?
    myfunc();
}

if (onceonly++ < 1)
    (function() { // do it })()

I know that last one won’t work exactly as is but it would if there were an already existing variable that defaulted to zero that I could “borrow”.

Also, anyone got an approach completely different from any of the above?

How can I make array in wich there are more than one date and the elements bellow have to change depending on wich element from the array is clicked

I want my “difference” to be an array with multiple dates. But date that is chosen should also be there date thats used bellow.

const difference = +new Date(`01/01/${year+1}`) - +new Date();

let timeLeft = {};

if (difference > 0) {
  timeLeft = {
    days: Math.floor(difference / (1000 * 60 * 60 * 24)),
    hours: Math.floor((difference / (1000 * 60 * 60)) % 24), 
    minutes: Math.floor((difference / 1000 / 60) % 60),
    seconds: Math.floor((difference / 1000) % 60)
  };
}

Uncaught in promise, failed to fetch when uploading file to AWS S3

I’m trying to upload files to S3, but am getting this error (I edited the name of the bucket).

mockServiceWorker.js:130 Uncaught (in promise) TypeError: Failed to fetch
    at mockServiceWorker.js:130:72
    at handleRequest (mockServiceWorker.js:135:7)
index.js:1227 
 POST https://name-of-bucket.s3-us-west-1.amazonaws.com/ net::ERR_ABORTED 400 (Bad Request)
localhost/:1 Uncaught (in promise) 
Response {type: 'cors', url: 'https://name-of-bucket.s3-us-west-1.amazonaws.com/', redirected: false, status: 400, ok: false, …}
body: (...)
bodyUsed: false
headers: Headers
[[Prototype]]: Headers
ok: false
redirected: false
status: 400
statusText: "Bad Request"
type: "cors"
url: "https://name-of-bucket.s3-us-west-1.amazonaws.com/"
[[Prototype]]: Response

This is the code I’m using.

import React, { useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import { nanoid } from '@reduxjs/toolkit'
import { postAdded } from './PostsSlice'
import S3 from 'react-aws-s3'

export function AddPostForm() {

//Removed

    const ReactS3Client = new S3(config)
    ReactS3Client.uploadFile(file, newFileName).then((data) => {
      console.log(data)
      if (data.status === 204) {
        console.log('success')
      } else {
        console.log('fail')
      }
    })
  //Removed rest of code
}

This is the CORS policy I’m using for S3. Does anyone know what I could be doing wrong? Does this have to do with CORS, or is it an issue with S3, or is there a syntax error?

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "PUT",
            "HEAD",
            "GET",
            "POST"
        ],
        "AllowedOrigins": [
            "http://localhost:3000"
        ],
        "ExposeHeaders": []
    }
]