Unknown file extension “.ts” appears when trying to run a ts-node script

I’m trying to run a script created in a regular folder with two .ts files. One with the script and one with helper functions to run it. I’m also importing more things such as axios or form-data.

The thing is that when I try to run the script with ts-node: node script.ts, the following error appears:

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"

My package.json:

{
  "dependencies": {
    "@types/node": "^17.0.23",
    "axios": "^0.26.1",
    "form-data": "^4.0.0",
    "showdown": "^2.0.3",
    "ts-node": "^10.7.0",
    "typescript": "^4.6.3"
  },
  "type": "module"
}

And my tsconfig.json:

{
  "compilerOptions": {
    "esModuleInterop": true
  },
  "include": ["/**/*.ts"],
  "exclude": ["node_modules"]
}

Does anyone know what I’m doing wrong? thanks!

Why is JavaScript code not working in Dreamweaver

I’m currently working on a school project where I have to create a website and include some sort of javascriptitng. We have to use Dreamweaver to write up our code html and css.

For some reason the code dose not work, im not sure why: i followed a youtube video for the JS code and there is no errors from what i know. Maybe its just because of dreamweaver. I have created a JS file and wrote my code in there and the file is in the root folder of the website. The file is also connected to the page, it my be connected wrong i really dont know what is wrong.

Here is the HTML CODE

Here is the JS code

Infer conditional return generic types by object property

I am trying to infer the generic type of Model per property. Everything currently is showing as unknown[] instead of the desired types in the comments below.

class Model<T> { }

type ArgumentType<T> = T extends Model<infer TInner> ? Model<TInner> : (
        T extends Model<infer TInner>[] ? Model<TInner>[] : never
    );

type ReturnType<T> = T extends Model<infer TInner> ? TInner[] : (
        T extends Model<infer TInner>[] ? TInner[][] : never
    );

const test = <TInner, TValue extends ArgumentType<TInner>, T extends Record<string, TValue>>(models: T): Record<keyof T, ReturnType<TValue>> => {

        return;
    }

const numberModel = new Model<number>();
const stringModel = new Model<string>();
const bigintModel = new Model<bigint>();

const result = test({
    prop1: [numberModel, numberModel, numberModel],
    prop2: [stringModel],
    prop3: stringModel,
    prop4: [numberModel, numberModel, numberModel, bigintModel],
    prop5: stringModel
});

//expected types
result.prop1 // number[][]
result.prop2 // string[][]
result.prop3 // string[]
result.prop4 // (number | bigint)[][]
result.prop5 // string[]

//actual types
result.prop1 // unknown[]
result.prop2 // unknown[]
result.prop3 // unknown[]
result.prop4 // unknown[]
result.prop5 // unknown[]

How to handle network errors or cancel network errors when using try/catch block in react native

I am using AWS services for my app, and got an error I have no idea how to handle or correct it.

When sending a post request using:

  const _publishPost = async () => {
    try {
      const newPost = {
        name: username,
        id: 12345678,
      };
      await API.graphql(graphqlOperation(createPost, { input: newPost }));
    } catch (e) { console.log(e); }
  }

When running it under low network I get the error:

  //AFTER A FEW SECONDS
  [ERROR] 14:41.398 axios-http-handler - Network Error
  at node_modules/@aws-amplify/core/lib-esm/Logger/ConsoleLogger.js:127:15 in prototype._log
  at node_modules/@aws-amplify/core/lib-esm/Logger/ConsoleLogger.js:210:8 in prototype.error
  at node_modules/@aws-amplify/storage/lib-esm/providers/axios-http-handler.js:178:20 in axios.request.then._catch$argument_0
  
  //AFTER WAITING A FEW MINUTE 
  [ERROR] 17:52.671 axios-http-handler - Request failed with status code 400
  at node_modules/@aws-amplify/core/lib-esm/Logger/ConsoleLogger.js:127:15 in prototype._log
  at node_modules/@aws-amplify/core/lib-esm/Logger/ConsoleLogger.js:210:8 in prototype.error
  at node_modules/@aws-amplify/storage/lib-esm/providers/axios-http-handler.js:178:20 in axios.request.then._catch$argument_0

I expected the error to be logged by the catch block and logged but the errors arent caught by the trycatch. I am not sure how I’d catch the error, cancel the request early enough and not let it freeze the app with a loading screen

I retried uploading it under the same network circumstace and I get the same error. With fair network connection it works perfectly.

*I am using expo to run the app

How to make a list of multiple variables in Javascript

Hi so I have a question that relates to a project that I am doing this is a example:

var result = 2;
var result1 = 3;
var result2 = 1;
var result3 = 5;
if (1 == (result,result1,result2,result3)){
    console.log("correct")  
}else{
  console.log("wrong")
}

so what I want this to is check all of the variables to see if any of them is equal to zero. Right now it does not check all of the variables. Thanks

React native set image to top

I am using react native to copy a bank app. However, the on the big picture, I created a screenshot of un functional component and inserted as an image.

The div is larger than the image and set a border of 1 px to see where is located.
I need to find a way please to align the image to the top and get rid of that padding from the top of the parent component. But nothing is working

  <View>
        <Image source={Icondet} resizeMode={'contain'}
        style={{
          width: '100%',
          borderWidth: 1
        }}/>
 </View>

This is the component I am trying to modify

enter image description here

The image is too low and there is so much padding.
How can I solve this please?

React Native component doesn’t get updated after adding data to Firestore

Coming back from another screen that adds data to Firestore, our ListUserTally.js component in the TallyScreen.js page (main page) doesn’t get updated. Right now, if we want to add data to the current date TallyScreen, we need to go to the EntryScreen.js screen, fill in the data, and hit confirm to add data to Firestore (that navigates us back to TallyScreen). To see the update we then need to change to a random date and come back to the current date in TallyScreen.

Tried re-rendering TallyScreen.js, force refresh, and using useEffect() to no avail.

Here is the code for those three pages:

TallyScreen.js

export default function TallyScreen({ navigation}) {
  const [date, setDate] = useState(new Date());
  const { uid } = firebase.auth().currentUser;
  const drawer = useRef();

  const menuNavigate = (nav) => {
    if (navigation.getState().routes[navigation.getState().index].name == nav)
      drawer.current.close();
    else {
      drawer.current.close();
      navigation.navigate(nav);
    }
  };

  return (
    <Drawer
      content={
        <Menu
          onBackPress={() => drawer.current.close()}
          onNavigate={(nav) => menuNavigate(nav)}
        ></Menu>
      }
      ref={drawer}
      styles={styles.container}
      type="displace"
      openDrawerOffset={220}
    >
      <View style={styles.container}>
        <NavbarItem onOpenDrawer={() => drawer.current.open()} />
        <ListUserTally setDate={setDate}/>
      </View>
      <ActionButton
        onPress={() =>
          navigation.navigate("EntryScreen", {
            date: date.toString(),
          })
        }
        buttonColor="#E5791C"
        size={60}
        shadowStyle={styles.addEntryButton}
      />
    </Drawer>
  );
}

ListUserTally.js

export default function ListUserTally(props) {
  const { uid } = firebase.auth().currentUser;
  const [listUserTally, setListUserTally] = useState([]);
  const [selectedDate, setSelectedDate] = useState(new Date());

  useEffect(() => {
    setListUserTally([]);
    getTodaysBagups();
  }, [selectedDate]);

  const getTodaysBagups = async () => {
    const currentDateMidnight = selectedDate.setHours(0, 0, 0, 0);
    const currentDate = new Date(currentDateMidnight);
    const nextDateMidnight = new Date(currentDate.getTime() + 86400000);
    const userData = await getUserDetails(uid);
    const allUsers = [];
    await firebase
      .firestore()
      .collection("users")
      .doc(uid)
      .collection("bagups")
      .where("date", ">=", currentDate)
      .where("date", "<", nextDateMidnight)
      .get()
      .then((snapshot) => {
        console.log(Tally.createTallyFromBE(snapshot, userData));
        allUsers.push(Tally.createTallyFromBE(snapshot, userData));
      })
      .catch((err) => {
        console.log("Error getting bagup documents", err);
      });
    setListUserTally(allUsers);
  };

  const getUserDetails = async (userId) => {
    let user = undefined;
    await firebase
      .firestore()
      .collection("users")
      .doc(userId)
      .get()
      .then((snapshot) => {
        user = snapshot.data();
      })
      .catch((err) => {
        console.log("Error getting bagup documents", err);
      });
    return user;
  };

  const setSelectedDates = (date) => {
    props.setDate(date);
    setSelectedDate(date);
  };

  return (
    <ScrollView contentContainerStyle={styles.scrollView}>
      <DateSelector
        setSelectedDates={setSelectedDates}
        selectedDate={selectedDate}
      />
      {listUserTally
        ? listUserTally.map((tally, id) => {
            if (tally.bagups.length > 0) {
              return (
                <CollapsableUserTally
                  key={id}
                  data={tally}
                  collapsed={id == 0 ? false : true}
                />
              );
            } else {
              return undefined;
            }
          })
        : undefined}
      <View style={styles.emptyView}>
        {/*Empty view to avoid visual obstruction by ActionButton*/}
      </View>
    </ScrollView>
  );
}

EntryScreen.js

export default function EntryScreen({ navigation, route }) {
  const [currentLanguage, setcurrentLanguage] = useState("ENGLISH");
  const [block, setBlock] = useState("");
  const [piece, setPiece] = useState("");
  const [centage, setCentage] = useState(null);
  const [bagupId, setBagupId] = useState(null);
  const [requestKey, setRequestKey] = useState("");
  const [bundleSize, setBundleSize] = useState(null);
  const [bundleCount, setBundleCount] = useState(null);
  const { uid } = firebase.auth().currentUser;
  const date = route.params.date;

  const inputBlock = useRef();
  const inputPiece = useRef();
  const inputCentage = useRef();
  const inputBagupId = useRef();
  const inputRK = useRef();
  const inputBS = useRef();
  const inputBC = useRef();

  const onConfirmPress = () => {
    if (inputVerification()) {
      firebase
        .firestore()
        .collection("users")
        .doc(uid)
        .collection("bagups")
        .add({
          block: block,
          piece: piece,
          centage: centage,
          id: bagupId,
          requestKey: requestKey,
          bundleSize: bundleSize,
          bundleCount: bundleCount,
          date: new Date(date),
        });
      
      
      navigation.navigate("TallyScreen");
    }
  };

  function inputVerification() {
    // https://aboutreact.com/react-native-check-textinput-is-empty-or-not/
    if (
      !block.trim() ||
      !piece.trim() ||
      !centage.trim() ||
      !bagupId.trim() ||
      !requestKey.trim() ||
      !bundleSize.trim() ||
      !bundleCount.trim()
    ) {
      alert("Please enter all values");
      return false;
    }

    // https://mkyong.com/javascript/check-if-variable-is-a-number-in-javascript/
    if (
      isNaN(centage) ||
      isNaN(bagupId) ||
      isNaN(bundleSize) ||
      isNaN(bundleCount)
    ) {
      alert(
        "Make sure centage, bag up id, bundle size, and bundle count are all numbers"
      );
      return false;
    }

    return true;
  }

  function getBagupRevenue() {
    return centage * bundleCount * bundleSize;
  }

  return (
    <View style={styles.container}>
      <HeaderRNE
        containerStyle={styles.navbar}
        centerComponent={{
          text: getText("HEADER_ADD_ENTRY", currentLanguage),
          style: styles.header,
        }}
        leftComponent={
          <TouchableWithoutFeedback
            onPress={() => navigation.navigate("TallyScreen")
          }
          >
          <Icon size={40} name="arrowleft" type="antdesign" />
          </TouchableWithoutFeedback>
        }
      />
      <View style={styles.container}></View>
      <TouchableWithoutFeedback onPress={() => inputBlock.current.focus()}>
        <View style={styles.inputBox}>
          <Icon name="terrain" type="fontawesome" style={styles.inputBoxIcon} />
          <TextInput
            ref={inputBlock}
            style={styles.inputBoxInput}
            placeholder={getText("BLOCK_PLACEHOLDER", currentLanguage)}
            onChangeText={(text) => setBlock(text)}
            value={block}
          />
        </View>
      (...)
      <Text style={styles.bagupInfoText}>
        {getText("BAGUP_REVENUE", currentLanguage)}
        {getBagupRevenue()}
      </Text>
      <View style={styles.confirmButtonView}>
        <View style={{ flex: 3 }}>
          <Button
            title={getText("CONFIRM", currentLanguage)}
            buttonStyle={styles.confirmButton}
            titleStyle={styles.confirmButtonText}
            onPress={() => onConfirmPress()}
          />
        </View>
      </View>
    </View> 
  );
}

PayPal Donate SDK – Prefill Amount and Frequency

I am building an application which includes a custom donation form where users can select:

  • Frequency: monthly, single
  • Amount: 3 x Buttons with values, input for custom value

enter image description here

I am using the PayPal Donate SDK and cannot find a way to pass across the amount or frequency so that the amount is pre-filled and the “make this a monthly donation” checkbox selected/deselected based on the users input.

The PayPal button has been added to the page (just absolute styled over the form button) and the SDK opens the donation page in a modal which is my desired result.

This is the code to display my button:

window.PayPal.Donation.Button({
    env: "sandbox",
    hosted_button_id: "xxxxxxxxxxxx",
    onComplete: function() {
        // Redirect to success page, save the PP transaction details, etc.
    }
}).render("#paypal-donate-button-container");

With the standard PayPal.Buttons API, I am able to pass in a createOrder function like so, where I can set the amount, for example;

window.PayPal.Buttons({
    createOrder: function(data, actions) {
        return actions.order.create({
            purchase_units: [{
                amount: {
                    value: document.querySelector(".selected-premium").dataset.value
                },
                reference_id: document.querySelector(".selected-premium").dataset.days + "-days"
            }]
        });
    }
}

Is there a way to pass through the amount and frequency using the SDK, similar to how I can do it with the standard payments API? If not, what are the alternatives in 2022 that don’t rely on SO answers that use docs that no longer exist?

How to make an array unique by object key?

How to make an array unique by object key?
I have dynamic checkboxes, whose id I put in the state.

In the format [checkBoxId]: e.target.value

And then I try to make a unique array from the received checked from the checkbox, but nothing comes out

[...new Map(
      myCheckboxes.map((item) => { // item {dfsd34534ftg: true} (dfsd34534ftg - id)
      const key = Object.keys(item);
      return [item[key], item];
   }),
).values()]

enter image description here

{response.map(({ id}, idx) => (
    <div key={id}>
       <Checkbox
          change={e => {
          setMyCheckboxes(prev => [
              ...prev,
              {
                [id]: e.target.checked,
              },
           ]);
          }}
          checked={myCheckboxes[idx]?.id}
       />
...

Recharts bar chart y-axis range not rendered in case of multiple bar charts on same page

I am using 4 re-charts barchart control in react to display bar charts in the same page. To set the y-axis range, I am using datamax. It is working for 2 of the barcharts but for the remaining 2, it does not work. Below is the Y-Axis configuration:-

<YAxis type="number" domain={[0, (dataMax) => Number(dataMax) + 50]} />

Below is the screenshot of the way the charts are currently rendered. The ones highlighted in yellow are not correctly rendered.

enter image description here

Is there a way to implement styles on dynamically generated div inside a component in React

In React, I have a component called DivHelper which generates 2 divs one below the other – instead i want to place them side by side and I cant see the code of Divhelper generates the divs. Is there a way to access dynamically generated divs ?

For example –

///Some random code

< DivHelper/>

///Some more code

This becomes

///Some random code

<div>1 Div</div>

<div>2 Div</div>

///Some more code

and thus, the output is

1 Div

2 Div

Instead I want it to be placed on side by side reversed (like float)
2 Div 1 Div

Is this possible ?

javascript when using multiple if conditions get the failure reason

Over the years there have been multiple answers to this question, evolving from some clunky code.

In 2022 is there a one liner or improved way to get the condition that failed in a multiple if scenario?

example one, myVarTwo fails

if (( myVarOne == "alpha") && ( myVarTwo == "beta") &&  ( myVarThree == "cappa"){
 // do stuff
 }else{
  console.log("failed at ...)
 }

example two, myVarThree fails

if (( myVarOne == "alpha") || (( myVarTwo == "beta") &&  ( myVarThree == "cappa")){
 // do stuff
 }else{
  console.log("failed at ...)
 }

I am assuming the conditions test stops at the first fail.

Call Web API to Update Custom Field on Post Save in WordPress

I need to grab some data from a web API and stick it in a custom field when the user hits update in WordPress. I have a js file that correctly gets the API data and am enqueueing the script with the code below. The problem is timing. The fetch call obviously comes in too late and the post is saved before I can add it to the custom field. Not sure how to set this up?

if ( $hook == ‘post-new.php’ || $hook == ‘post.php’ ) {
if ( $post->post_type == ‘speakers’ ) {
wp_enqueue_script( ‘test’, get_stylesheet_directory_uri() . ‘/js/test.js?v=111’, ‘jquery’, ”, true );
}
}

Plus – I have to make the API call in the browser, not server side.

Any help would be amazing! Thanks!

Why isn’t data being pulled from database when I load the page?

I have a button that’s supposed to run a function when loaded.

<LikeButtonStyle onLoad={getUserData} onClick={addInfo}>

the function it’s supposed to run is

async function getUserData() {
    const docSnap = await getDoc(userCollectionRef);
    if (docSnap.exists()) {
      setUser(docSnap.data().username);
      setUserLikes(docSnap.data().likePost);
      if (userLikes == 'no') {
        setLikeCount('0');
      } else {
        setLikeCount('1');
      }
    }
  }

So the idea is that when the page loads, it grabs the user data which is made up of two fields username and likePost. Once it grabs that data it’s supposed to set that data in state.

It uses this data to count a 0 or 1 depending if the user has liked it or not.