Getting download error while using fetch to download PDF in React app

I am trying to create a button that downloads a PDF in my React component. I have tried several different ways to achieve with no luck. The code below is the closest I’ve gotten. If I click the button, the pdf downloads but when I open the download it has an error “Failed to load PDF document.”

Any ideas how to fix?

  const onButtonDownloadSales = () => {
    fetch('TermsEquipSales.pdf').then(res => {
      res.blob().then(blob => {
        const fileURL = window.URL.createObjectURL(new Blob([blob]));
        let alink = document.createElement('a');
        alink.href = fileURL;
        alink.setAttribute('download', 'TermsEquipSales.pdf')
        document.body.appendChild(alink)
        // alink.download = 'TermsEquipSales.pdf'
        alink.click()
        alink.parentNode.removeChild(alink)
      })
    })
  }


 <Box>
     <button onClick={onButtonDownloadSales}>
       Standard Terms and Conditions for the Sale of Equipment
     </button>
 </Box>

JS: logging data

I am new to JS and ran into a problem. Here is a simple javascript snippet that wants to be used in PCIbex Farm.

It goes through asking questions from a CSV file and waits for text input for every given question. If there are at least 8 characters typed in the input, it jumps to the next sentence after pressing Enter/Return key. It logs the output data to the console, however, I want to store it in the log file and process it later.

How I can do it? If I just simply use log() then the resolve seems to be not called as I am stuck in the first question.

Template("Poodle-items.csv", row =>
  newTrial("experimental-trial",
    newHtml("content",
      `<div style="display: inline-block;">
        <input type="text" id="sentence" name="sentence" style="width: 200px; height: 20px;">
      </div>
      <div style="display: inline-block;">
        <p>${row.sentence}</p>
      </div>
      <div id="errorMessage"></div>`
    )
    .print(),

    newFunction(() => {
      const sentenceInput = document.getElementById("sentence");
      const errorMessage = document.getElementById("errorMessage");

      let errorMessageDisplayed = false;
      let resolveFunction;

      sentenceInput.addEventListener("keyup", function(event) {
        if (event.key === "Enter") {
          if (sentenceInput.value.length < 8 && !errorMessageDisplayed) {
            const errorText = document.createElement("p");
            errorText.textContent = "Please write a longer answer!";
            errorText.classList.add("errorMessage");
            errorMessage.appendChild(errorText);
            errorMessageDisplayed = true;
          } else if (sentenceInput.value.length >= 8) {
            errorMessage.innerHTML = ""; // Clear previous error message

            // Log the data
            const dataToSave = `sentence: ${sentenceInput.value}ngroup: ${row.group}nconjunction: ${row.conjunction}ndegree: ${row.so}nID: ${getVar("ID")}nn`;
            resolveFunction();
            console.log(dataToSave);
          }
        }
      });

      return new Promise(resolve => {
        resolveFunction = resolve;
      })
;
    })
    .call()
  )
);

I tried using log(), but it did not work, as I stucked at the first question (looked like log interfered with resolve). If I use console.log() I can see the data on the console, but it is not stored after the experiment is done.

Return conditional rendering in React doesn’t show Fetch elemets

Hey guys thanks for your time. I’m still new to React so I’m trying to learn how to use it. I’m retrieving items from an API and after I’m getting a success, I push the setState to create the new components from the response – and I don’t have any problems with that.
But I was trying to render two different components, one for the loading state when we are waiting for a response from the server, and the actual elements. And I know there is a way to do it with a ternary condition. But I think an anonymous function looks better. And this works well with the “Loading…” state, but after I get the response from the server, it doesn’t display anything. If I’ll throw even static data there – it doesn’t show. How this thing works like? Cause If I’ll debug each element in map – I’ll have my response – but It just don’t want to render them.

export function Main(){

  const [state, setState] = useState({users: []});
  const temporaryUsers = state.users;
  useEffect(() => {
      fetch(`https://randomuser.me/api/?results=20`)
      .then(res => res.json())
      .then(json => {
        temporaryUsers.push(json);
        setState({
          users: temporaryUsers
        });
      });
        
    },[])
  
      return(
        <>
          {(() => {
            if (state.users[0] != undefined){
              state.users[0].results.map((elem) => {
                return(
                  <User  props={elem} />
                )
              })
              
            } else{
              return (
                <p style={{textAlign:"center", display:"block", width:"100%"}}>Loading...</p>
              ) 
            }
          })()}
        </>
        
      )
  
}

How to prevent users from reacting to multiple emojis in a Discord.js poll bot?

Versions:
discord.js: [email protected]
Node: v20.2.0

I’m trying to make a poll bot based on reactions and I’m trying to limit reactions so that each user can only be reacted to one emoji at a time. Currently I have a system that checks if a user is already reacted and if so, removes and new reactions until they remove their original reaction but I’m wondering if a system that would remove the old reaction is instead possible? This is the current system I have for the limiting.

This is my current code that removes any new reactions but I’d like to make it remove the old reaction instead. Is this even possible?

interaction.client.on("messageReactionAdd", async (reaction, user) => {
  //Check that the reaction is not a partial
  if (reaction.message.partial) await reaction.message.fetch();
  if (reaction.partial) await reaction.fetch();

  /*Check if:
  the reactor is not a bot,
  if the reaction is in a DM,
  if the message reacted to is the poll for this interaction,
  if the poll has ended and return if any are true */
  if (
    user.bot ||
    !reaction.message.guild ||
    pollMessage.id != reaction.message.id ||
    timedOut
  )
    return;

  //No new reactions emojis can be added
  if (!reactionEmojis.includes(reaction._emoji.toString())) {
    reaction.users.remove(user.id).catch(console.error);
    return;
  }

  const { message } = reaction;
  let member = reaction.message.guild.members.cache.get(user.id);

  //Limit reactions to member if need be
  if (roleID != null) {
    if (!member.roles.cache.has(roleID.value)) {
      reaction.users.remove(user.id).catch(console.error);
      return;
    }
  }

  if (!reactionCount.get(message))
    reactionCount.set(message, new Collection());
  const userCount = reactionCount.get(message);
  userCount.set(user, (userCount.get(user) || 0) + 1);

  if (userCount.get(user) > 1) {
    reaction.users.remove(user);
    return;
  }
  const pollMessageString = await generatePollBars(
    pollMessage,
    votingOptions
  );
  pollEmbed.setDescription(pollMessageString);
  await pollMessage.edit({ embeds: [pollEmbed] });
});

interaction.client.on("messageReactionRemove", async (reaction, user) => {
  if (reaction.message.partial) await reaction.message.fetch();
  if (reaction.partial) await reaction.fetch();
  if (
    user.bot ||
    !reaction.message.guild ||
    pollMessage.id != reaction.message.id ||
    timedOut
  )
    return;

  const { message } = reaction;
  const userCount = reactionCount.get(message);
  // subtract 1 from user's reaction count
  try {
    userCount.set(user, reactionCount.get(message).get(user) - 1);
  } catch (TypeError) {}
  const pollMessageString = await generatePollBars(
    pollMessage,
    votingOptions
  );
  pollEmbed.setDescription(pollMessageString);
  await pollMessage.edit({ embeds: [pollEmbed] });
});

How to replace a negating character group with a regex group?

This is the original regex pattern using a negating character group:

0[^1]*1[^2]*2[^3]*3

It will match 0 1 2 3 efficiently with any delimiting character between digits using a greedy quantifier, compared to the lazy 0.*1.*2.*3 which becomes inefficient very quickly for long test strings.

How can the same efficiency be achieved when instead of single characters, it should match groups of characters, for example for this test string:

zero one two three

I was thinking to use a negative lookahead, but this for example doesn’t work:

zero(?!(two)*)two...

In other words, I’m looking for an efficient regex that matches zero one two three where the delimiting characters in between can be any combination of characters of any length, so it should also match for example zero-one, two xxx three.

What’s the solution?

(RegEx engine ECMA Script / JavaScript)

How could i set a path from my location to a marker

I’m trying to set a path from my location to my markers on the map with a click on the marker.

I have the location (the blue point) and the markers on the map: You can se here

I’ve tried to do it with the directions api but i was getting an error because of the billing(google not accepting pre-paid cards)

this is the code:

import React, { useEffect } from "react";
import {
  StyleSheet,
  Text,
  TextInput,
  View,
  ScrollView,
  Animated,
  Image,
  TouchableOpacity,
  Dimensions,
  Platform,
} from "react-native";

//theme
import { useTheme } from "@react-navigation/native";

//fast image
//import FastImage from 'react-native-fast-image'

//icons
import IonIcon from "react-native-vector-icons/Ionicons";

//map imports
import MapView, { Marker, PROVIDER_GOOGLE,Callout} from "react-native-maps";

import MapViewDirections from 'react-native-maps-directions';

import { markers, mapDarkStyle, mapStandardStyle } from "../model/mapData";
import StarRating from "../components/startRating";


//user location
import * as Location from 'expo-location';

const ExploreScreen = () => {
  const theme = useTheme();


  const initialMapState = {
    markers,
    region: {
      //initial region location (mindelo)
      latitude: 16.876546,
      longitude: -24.98135,
      latitudeDelta: 0.015,
      longitudeDelta: 0.0121,
    },
  };
  
  const [state, setState] = React.useState(initialMapState);
  
  const _map = React.useRef(null);
  
  //to get user location
  const [location, setLocation] = React.useState(null);
  const [errorMsg, setErrorMsg] = React.useState(null);

  React.useEffect(() => {
    (async () => {
      
      let { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        setErrorMsg('Permission to access location was denied');
        return;
      }
      let location = await Location.getCurrentPositionAsync({accuracy:Location.Accuracy.Highest, maximumAge: 10000}); //Accuracy to get the best location possible
      setLocation(location);
    })();
  }, []);

  return (
    <View style={styles.container}>
      <MapView
        ref={_map}
        initialRegion={state.region}
        provider={PROVIDER_GOOGLE}
        style={styles.map}
        mapType="satellite"
        showsUserLocation={true}
        customMapStyle={theme.dark ? mapDarkStyle : mapStandardStyle}
      >
        {state.markers.map((marker, index) => {
          return (
            <Marker
              optimizeWaypoints={true}
              tracksViewChanges={false}
              key={index}
              coordinate={marker.coordinate}
              // title={marker.title}
              // description={marker.description}
              onCalloutPress={() => alert('clicked')}
            >
              <Animated.View style={styles.content}>
                <View style={styles.ballon}>
                  <Image source={marker.image} style={styles.imgEvent} resizeMode="cover"></Image>
                </View>
              </Animated.View>
              <Callout tooltip= {true}>
                <View style={[styles.card]}>
                  <Text> 
                  <Image
                    style={styles.cardImage}
                    source={marker.image} />
                    </Text>
                  <View style={styles.textContent}>
                    <Text numberOfLines={1} style={styles.cardtitle}>{marker.title}</Text>
                    <StarRating rating={marker.rating} reviews={marker.reviews}></StarRating>
                    <Text numberOfLines={1} style={styles.cardDescription}>{marker.description}</Text>
                    <View style={styles.button}>
                      <TouchableOpacity style={[styles.signIn, { borderColor: '#FF6347' }, { borderWidth: 1 }]}>
                        <Text style={[styles.textSign, { color: "#FF6347" }]}>Comment about the event</Text>
                      </TouchableOpacity>
                    </View>
                  </View>
                </View>
              </Callout>
            </Marker>
          );
        })}
  
      </MapView>
      {/* Search Box  */}
      <View style={[styles.searchBox, { borderRadius: 10 }, { padding: 7 }]}>
        <TextInput
          placeholder="Search here"
          placeholderTextColor="#000"
          autoCapitalize="none"
          style={{ flex: 1, padding: 0 }}
        ></TextInput>
        <IonIcon
          name="ios-search"
          size={20}
          style={{ paddingTop: 3 }}
        ></IonIcon>
      </View>
    </View>
  );
};
export default ExploreScreen;

How to display a 3D object (*.stl file) using Django

I have a website developed using Django. Several 3D object files (*.stl files) are loaded from the administration. I would like to add the following two functionalities.

1- Being able to view 3D objects, both for an administrator and for a regular user.
2- In case of being a regular user, the object is only downloadable, under some conditions (for example if the user pay for the article.)

The following site is a good benchmark of what I want. sketchfab

I don’t even know how to proceed, any comment would be welcome.

How to embed the toggle into the mat-options in angular?

I need to embed the toggle button or radio button inside the mat-options list. The desired design is as follows.

enter image description here

ISSUE:

I have added the toggle button inside the options list with the following code but by clicking on the toggle button the option is checked or unchecked rather than changing the toggle state.

<mat-option (click)="handleSelected(item)" *ngFor="let item of defaultSelectValue | dataSearch : field.searchCtrl.value" [value]="field.keySelect ? item[this.field.selectKey] : item">
    {{ item[this.field.selectValue] }} 
<mat-slide-toggle></mat-slide-toggle>
</mat-option>

Please guide me that, How can I achieve it in a way that both things work correspondingly?

Vue with XMLHttpRequest of Google Calendar API

I have a function in my VueJS app which is attempting to load a Google Calendar

loadCalendar() {
    var comp = this;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://www.googleapis.com/calendar/v3/calendars/primary/events');                                   
    xhr.setRequestHeader('Authorization', 'Bearer' + comp.access_token, true);
    console.log("comp access token is = " + comp.access_token)
    xhr.send();
   }

And I have retrieved an access token, using Google’s client.requestAccessToken that is stored against access_token.

Unfortunately, I am receiving a 401 error of The request is missing a valid API key.

I have also tried appending the API key to the URL as: 'https://www.googleapis.com/calendar/v3/calendars/{calendar_id}?key=[YOUR_API_KEY]'

Any advice on how I fix this is much appreciated. Many thanks.

Recreating a split screen with a sticky side

I’ve looked at multiple other posts on this topic however I can’t find one that replicates the feature I’m looking for exactly. What I’m trying to accomplish is something similar to the “We make scheduling for you easier than ever” section on https://calendly.com/. As you can see, when the user scrolls through, the image on the right becomes sticky once it’s in the center of the right half of the screen, and as you scroll through the paragraphs on the left, the image fades into different images. I’m trying to recreate this exactly, but it’s not working out at all. I’ve tried using js to calculate the scroll percentage and based upon that, fade the image out and the new image in, but it just doesn’t work at all. Any help would be appreciated and thank you in advance.

Callback refs not trigger when ref value changes in React

I am using useCallback to observer ref callback value changes but I getting only one node printed in console. How I can observer ref value changes ?

  const myRef = useRef(null);

  const refObserver = useCallback(node => {
    if (node) {
      console.log(node); // print one time only 
    }
  }, []); 

  return (
    <>
       <div ref={refCb => {
           myRef.current = refCb;
           refObserver(refCb);
       }}>
          Hello world!
       </div>

       <button onClick={() => {
          myRef.current.innerText = `${Math.random()}`;
       }}>
          Change text!
       </button>
    </>
  )

What IS a web worker?

What exactly is a “web worker”, where does it come from, and what is it used for? What is the syntax to create one?

I’m not interested in the difference between web workers and service workers (I’ve seen enough questions talking about those)

How to dynamically inline SVGs in React/Next.js so I can apply direct styling

I’m building a component that renders icons associated with a set of keywords. The icon will be different each time the component is used, so I could just us a direct path to the SVG file as the src of an image tag. However I need to style the fill of these SVGs with a color which is also a prop. I can’t find a way to inline the SVG based on a variable.

I can loop my data and use this very simple component to render each icon. But not inlined so I cant apply any style:

export default function ExtraIcon({ name, color }) {
  return (
    <div className="extra-icon column is-2">
      <div>
        <Image
          src={`/images/icons/${name}.svg`}
          width={80}
          height={80}
          alt={name}
        />
      </div>
      {name}
    </div>
  );
}

I’ve found a solution to this using @tanem/svg-injector but this works with a client side call after the component has rendered, and selects via DOM element ID which doesn’t feel optimal.

export default function ExtraIcon({ name, color }) {
  useEffect(() => {
    SVGInjector(document.getElementById(`inject-${name}-svg`), {beforeEach(svg) {
      svg.setAttribute('fill', color)
    }});
  }, []);
  
  return (
    <div className="extra-icon column is-2">
      <div
        id={`inject-${name}-svg`}
        data-src={`/images/icons/${IconsMap[name]}.svg`}
      ></div>
      <div className="extra-icon__name">{name}</div>
    </div>
  );
}

I could possibly use fs to read the file and then createElement. That feels both convoluted and also against the Next.js approach. I also think I would need to do that in getServerSideProps and then pass down all the data of all the SVGs from the page component to this ExtraIcon component.

What am I missing? Or is this all too against the conventions of Next and I either live with client side injection or try to change the design?

How to avoid update the original object when I update the object in other var? [duplicate]

I have this original array objects:

const students=[
  { "name": "sean"},{"name":"paula"}
];

I am trying to update the object where student.name==="sean" to "jason"

I want to avoid update the original array object

console.log(students); // should be {"name": "jason"},{"name": "paula"}
console.log(findStudent); //output is {"name":"jason"} (desired result)

const students=[
  { "name": "sean"},{"name":"paula"}
];

const findStudent= students.find((student)=>student.name==="sean");
findStudent.name="jason";
console.log(findStudent); //output is {"name":"jason"} (desired result)
console.log(students); // output is {"name": "jason"},{"name": "paula"} (wrong result)

, how to avoid it?

How to update nested documents in mongoose nodejs?

Hey guys I am struggling with updating a nested document w mongoose

flashcardDeck.updateOne({ _id: deck._id }, { $set: { flashcards[Math.floor(i/2)].side1: newFlashcardsArr[i]}});

for some reason the editor throws errors when I try to specify which flashcard to update.
Does anyone know why this is happening?