Immutable date, datetime and timedelta library for react native

Coming from python I am having a very hard time adapting to the way dates and datetimes are handled in javascript/typescript.

I’d rather not use moment.js as it is considered legacy and I’d really like to have immutable objects.

Luxon is not a good choice for me either because it means I have to eject from expo go. I do not have a mac so I have to use my wifes iPhone, which means I am stuck to this app.

date-fn requires me to set the locale manually on every localization request.

In short I would like to have a javascript library that can localize immutable datetime objects out of the box, has support for timedeltas (or intervals, or durations) and if possible has support for non-localized time objects.

I don’t believe this is an uncommon problem and yet those are the only 3 libraries I keep finding.

How to handle 3 different conditions in a React functional component

I am rendering out a lists of posts. There are 3 different types of content these posts will show. So the list view of all of these posts is the same. Standard title, thumbnail, author, etc. But when you go to the page of these 3 different types the content renders a different layout (different component). I have a simple ternary operator to set the different links for 2 of the link types. But now that I have 3 what is the best practice to setup that logic?

Here is what I have so far:

 <div className="all-posts">
                    { currentPosts?.map(post => (
                        <Link key={post.id} className="link-wrapper" to={post.course_trailer ? `course/${post.id}` : `/lesson/${post.id}`}> 
                            <div  className="post-container">
                                <div className="thumbnail-container">
                                 <img className="post-thumbnail" src={post.course_trailer ? post.featured_image : post.app_thumbnail} alt="" />
                                </div>
                                <div className="post-meta">
                                    <p className="post-title">{post.title}</p>
                                    <div className="author-meta">
                                        <div className="author-container">
                                            <p className="post-teacher">@{post.instructor_name}</p>
                                            <img className="verification-badge" src="#" alt="" />
                                        </div>
                                        <p className="post-views">Views: {post.views}</p>
                                    </div>
                                </div>
                            </div>           
                        </Link>
                    ))
                    }  
    </div>

You see in the Link I have the ternary. Now I need to setup the logic like if post.course_trailer go to this path if post.formulas then go to this path else go to the standard path.

Iterate over table using puppeteer

I want to get data from a website which is in table. First i try to get the whole table and then get the tr‘s and td‘s that are inside it. The code i have now just return empty array.

const puppeteer = require("puppeteer");

async function run() {
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();
  await page.goto(
    "https://www.basketball-reference.com/leagues/NBA_2021_standings.html" //Eastern Conference
  );

  var temp = [];
  const data = await page.evaluate(() => {
    const tableBody = document.querySelector(
      'table[id="confs_standings_E"] tbody'
    );

     for (var i = 0; i < tableBody.length; i++) {
      const tr = tableBody[i].querySelectorAll("tr");
      for (var j = 0; j < tr.length; j++) {
       const td = tr[j].querySelectorAll("td").innerText;
       temp.push(td);
  }
}
  });

  console.log(temp);
  //await browser.close();
}

run();

Thanks for any help

Invalid hook call. How to set a value with react axios get call?

I have this react component that has a simple form where, when you put a superhero name, it makes an axios get request to an API that responds successfully with json object with info of said hero. That info is stored in the state and then mapped through to create a grid. It used to work just fine as a class element so I started doing other parts of the app that have nothing to do with this part, but when i run the whole app again so check i get an hook call error in this component.

This is the seeker component, i did the class and the funcion version.

import React, { useState } from "react";
import { Formik, Form, Field, ErrorMessage } from 'formik';
import axios from "axios";
require("babel-core/register");
require("babel-polyfill");
import grid from "../components/grid";


/* 
const Seeker = () => {
   const fetchData = (data) => {axios.get(`https://www.superheroapi.com/api.php/1589015884770221/search/${name}`)
       .then((response) => {
           localStorage.setItem("addHeroAction", true);
           let results = response.data.results;
           localStorage.setItem("matchedHeros", results);
       }).catch((error) => {
           console.log(error)
       })
   }

   let matchedHeros = localStorage.getItem("matchedHeros") ? localStorage.getItem("matchedHeros") : [];
   
   const gridRender = (response) =>{
       if(response.length && response != undefined){
           console.log(response)
           return( 
           <div className="grid__background">
           <div className="grid">
               <div className="grid__box grid__top grid__top--container"></div>
               <div className="grid__box grid__top grid__top--container"><h2>Name</h2></div>
               <div className="grid__box grid__top grid__top--container"><h2>Intelligence</h2></div>
               <div className="grid__box grid__top grid__top--container"><h2>Strenght</h2></div>
               <div className="grid__box grid__top grid__top--container"><h2>Speed</h2></div>
               <div className="grid__box grid__top grid__top--container"><h2>Durability</h2></div>
               <div className="grid__box grid__top grid__top--container"><h2>Power</h2></div>
               <div className="grid__box grid__top grid__top--container"><h2>Combat</h2></div>
               <div className="grid__box grid__top grid__top--container"></div>
               {response.map(hero => grid(hero, hero.id))}
           </div>
           </div>)
       } else {
           return (<div></div>)
       }
   }

   return (
       <div>
           <h1>Find your next teammate!</h1>
               <Formik
               initialValues={{ name: ''}}
               validate={values => {
                   const errors = {};
                   if (!values.name) {
                       errors.name = 'Required';
                   } else if (
                       !/^[a-zA-Z]*$/.test(values.name)
                   ) {
                       errors.name = 'Invalid name';
                   }
                   return errors;
               }}
               onSubmit={(values) => {
                   console.log(fetchData(values.name));
               }}
               >
               {() => (
                   <Form>
                   <Field type="text" name="name" />
                   <ErrorMessage name="name" component="div" />
                   <button type="submit">
                       Submit
                   </button>
                   </Form>
               )}
               </Formik>
                   {gridRender(matchedHeros)}
       </div>
       )
   } */


   class Seeker extends React.Component{
   state = {
       matchedHeros : [],
       loadingData : true
   }
   constructor(){
       super();
       this.fetchData = this.fetchData.bind(this);
   }

   
   fetchData = async (name) => {
       if(this.state.loadingData){
           await axios.get(`https://www.superheroapi.com/api.php/1589015884770221/search/${name}`)
           .then((response) => {
               localStorage.setItem("addHeroAction", true);
               this.setState({matchedHeros : response.data.results, loadingData : false});
           }).catch((error) => {
               console.log(error)
           })
       }
  
       
   }     

   
   render(){
       return (
           <div>
               <h1>Find your next teammate!</h1>
                   <Formik
                   initialValues={{ name: ''}}
                   validate={values => {
                       const errors = {};
                       if (!values.name) {
                           errors.name = 'Required';
                       } else if (
                           !/^[a-zA-Z]*$/.test(values.name)
                       ) {
                           errors.name = 'Invalid name';
                       }
                       return errors;
                   }}
                   onSubmit={(values) => {
                       this.fetchData(values.name);
                   }}
                   >
                   {() => (
                       <Form>
                       <Field type="text" name="name" />
                       <ErrorMessage name="name" component="div" />
                       <button type="submit">
                           Submit
                       </button>
                       </Form>
                   )}
                   </Formik>
                   {console.log(this.state.matchedHeros)}
                   {this.state.matchedHeros.length ?  
                       (
                       <div className="grid__background">
                           <div className="grid">
                               <div className="grid__box grid__top grid__top--container"></div>
                               <div className="grid__box grid__top grid__top--container"><h2>Name</h2></div>
                               <div className="grid__box grid__top grid__top--container"><h2>Intelligence</h2></div>
                               <div className="grid__box grid__top grid__top--container"><h2>Strenght</h2></div>
                               <div className="grid__box grid__top grid__top--container"><h2>Speed</h2></div>
                               <div className="grid__box grid__top grid__top--container"><h2>Durability</h2></div>
                               <div className="grid__box grid__top grid__top--container"><h2>Power</h2></div>
                               <div className="grid__box grid__top grid__top--container"><h2>Combat</h2></div>
                               <div className="grid__box grid__top grid__top--container"></div>
                           </div>
                       </div>
                       )
                       :
                       <div></div>
                   }
                   {this.state.matchedHeros.map(hero => grid(hero, hero.id))}
           </div>
           )
   }
} 


export default Seeker; 

It uses the formik library to verified the values and the it maps the info with a Grid component that works just fine on its own, so the problem is in this component. The axios call also sets a value in localStorage that i need to be set when the button is clicked.

The original was the class component but with it I have this error on the console.

“Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component.”

Then i made the functional component version, which is commented in the code above, but with it i can’t get the state updated with axios.

When i look into someone else’s examples they look like mine but I still get the hook call error, i already checked that i have up-to-date versions of react so that’s not the problem.
What am I doing wrong? or else, what suggestion can you guys give me to achieve the same result?

Global event listener with DataTables

As you can see below, I have an event listener within the processServiceConsumers function. How can I have it outside the functions so it’s a global event listener?

function getServiceConsumers() {
    
    return $.ajax({
        url: baseURL + "serviceConsumers?connectionPointId=" + ntjpProdConnectionPointId,
        success: function(result){
            processServiceConsumers(result);
        }
    });
    
}

function processServiceConsumers(data) {
    
    $("#serviceConsumersWrapper").show();
    
    var serviceConsumersTable = $('#serviceConsumersTable').DataTable( {
        data: data,
        dataSrc: "",
        columns: [
                { data: "id", orderData: 2 },
                { data: "hsaId" },
                { data: "description" }
            ],
        select: true
    } );
    
    serviceConsumersTable.on( 'select', function () {

        var selectedRowId = serviceConsumersTable.rows( { selected: true } ).data()[0].id;
 
        // getServiceContracts(selectedRowId);
        
    } );

}

Is there a property like word-wrap or overflow-wrap that can force breaks at word boundaries?

For example, If I have a sentence like the following:

I like cute dogs because they’re awesome

doing something like word-break: break-word might give you

I like cute dogs because they’re awe

some

The behavior I want is for it to break like

I like cute dogs because they’re

awesome

I can’t seem to find a way to do this. In most cases, the words do seem to fit efficiently into the container, but there are weird cases with long words that spill out even though I would think it should know how to rearrange them for this not to happen. The words aren’t even close in length to the width of the container, so it’s not that what I’m trying to achieve is impossible or anything. The CSS I have written is so negligible that it’s probably not even worth including, but it’s something like:

.someClass {
   margin-bottom: 2rem;
   padding: 0.5rem;i 
}

p {
   font-size: 1.1rem;
   margin-bottom: 0.375rem;
}

.someClass’s size is a fixed value, and its parent is a flex container. I tried adjusting the available space of the flex cell it occupies to exactly the size of the contained element but it made no difference.

  1. Why do words which are only a fraction of the width of the parent overflow sometimes? Like, why aren’t they auto arranged to divide the space without overflowing?
  2. Is there a way to ensure no overflow but without breaking mid-word, and instead breaking at word boundaries

Thanks for the help and cheers.

Library – adding books – HTM, CSS, JavaScript

I didn’t find a reply so I’m creating a new post. I’m a newbie into JS and I’d like to create a kind of library.
Explanation:
We have a form with input “user” and “author” and “category”
Button – to submit form.
I’d like to display data from my form under it (like on the attached screenshot).

My problem is that I don’t especially know how to display new data from the form (please take a look at code). I’m certainly sure that I should kind of a loop to create and display new UL with nested LI but I don’t know how :/.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="">
        <label for="title"></label>
        <input type="text" name="title" id="title">
        <label for="author"></label>
        <input type="text" name="author" id="author">
        <label for="category"></label>
        <select name="category" id="category">
            <option value="fantasy">Fantasy</option>
            <option value="sci-fi">Sci-Fi</option>
            <option value="romans">Romans</option>
        </select>
        <button type="submit" id="submit">Zatwierdź</button>
    </form>
    
    <script src="script.js"></script>
</body>
</html>
class Book {
    constructor(title,author,category) {
        this.title = title;
        this.author = author;
        this.category = category;
    }
}

let btn = document.getElementById('submit');

let books = [];

function submitForm(event) {
    event.preventDefault();
    
    let title = document.getElementById('title').value;
    let author = document.getElementById('author').value;
    let category = document.getElementById('category').value;

    let book = new Book(title,author,category);

    books.push(book);

    let elementUl = document.createElement('ul');

    function addElement() {
        
        let elementTitle = document.createElement('li');
        let elementAuthor = document.createElement('li');
        let elementCategory = document.createElement('li');
    
        let titleContent = document.createTextNode("Title: " + books[0].title);
        let authorContent = document.createTextNode("Author: " + books[0].author);
        let categoryContent = document.createTextNode("Category: " + books[0].category);
           
        elementTitle.appendChild(titleContent);
        elementAuthor.appendChild(authorContent);
        elementCategory.appendChild(categoryContent);
    
        elementUl.appendChild(elementTitle);
        elementUl.appendChild(elementAuthor);
        elementUl.appendChild(elementCategory);
    
        document.querySelector('body').appendChild(elementUl);
    }  

    addElement();
      
}

btn.addEventListener('click',submitForm);

how to add an array to my HTML body with a API [duplicate]

I would like to know how I can make an API arrangement appear directly in my HTML body, because when I try to do it it returns [object, object]

This is the array in console:

code: “IT”
confirmed: 12134286,
country: “Italy” ,
critical: 343 ,
deaths: 754169

This is my code:

const body = document.querySelector('body')
const button = document.querySelector('.button')

const result = () => {
  fetch("https://covid-19-data.p.rapidapi.com/country/code? 
  code=it", {
  "method": "GET",
  "headers": {
     "x-rapidapi-host": "covid-19-data.p.rapidapi.com",
      "x-rapidapi-key": "596ab7b883msh9846bfe9508ejsn1508f3534ee0"
  }
})
       .then(response => response.json())
       .then(data => {
         data.forEach(result => {
          console.log(result)
          const h2 = document.createElement('h2')
          h2.innerHTML = result
          body.appendChild(h2)
        })

     .catch(err => {
       console.error(err);
     });
    }

 button.addEventListener('click', () =>{
  result();
})

How to operate two set of tabs separately in HTML?

I am trying to operate different sets of tabs separately but it is not working properly. Tab 1, 2, and 3 belong to the first set of tabs whereas Tab A, B, and C belong to the second set of tabs. Tab 1 and Tab A should be opened by default when the page is loaded.

What are the necessary changes to be made to achieve the goal?

<!DOCTYPE html>
<html>
<head>
<style>
.tab1 button.active {
  background-color: #03a1fc;
}
.tab2 button.active {
  background-color: #03a1fc;
}
.tabcontent {
  display: none;
}
</style>

</head>
<body>

<div class = "tab1">
  <button class = "tablinks" id="defaultOpen1" onclick="openTab1(event, 't11')">1</button>
  <button class = "tablinks" onclick="openTab1(event, 't12')">2</button>
  <button class = "tablinks" onclick="openTab1(event, 't13')">3</button>
</div>

<div id="t11" class="tabcontent">
  <p>tab 1</p>
</div>

<div id="t12" class="tabcontent">
  <p>tab 2</p> 
</div>

<div id="t13" class="tabcontent">
  <p>tab 3</p>
</div>


<br><br><br>
<div class = "tab2">
  <button class = "tablinks" id="defaultOpen2" onclick="openTab2(event, 'tA')">A</button>
  <button class = "tablinks" onclick="openTab2(event, 'tB')">B</button>
  <button class = "tablinks" onclick="openTab2(event, 'tC')">C</button>
</div>

<div id="tA" class="tabcontent">
  <p>tab A</p>
</div>

<div id="tB" class="tabcontent">
  <p>tab B</p> 
</div>

<div id="tC" class="tabcontent">
  <p>tab C</p>
</div>


<script>
function openTab1(evt, tabName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(tabName).style.display = "block";
  evt.currentTarget.className += " active";
}

function openTab2(evt, tabName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(tabName).style.display = "block";
  evt.currentTarget.className += " active";
}

document.getElementById("defaultOpen1").click();  
document.getElementById("defaultOpen2").click(); 
</script>

</body>
</html> 

SuiteScript 2.x entry point scripts must implement one script type function

I added a field in the Sales Order named Membership that will source from the customer record. Then when that field is set to the membership level (ex. elite member) it automatically set the discount item field to a specific discount item…. I encountered a notif saying SuiteScript 2.x entry point scripts must implement one script type function how do I fix this?

/**
*@NApiVersion 2.x
*@NScriptType ClientScript
*/
define([“N/currentRecord”, “N/runtime”], function(currentRecord,runtime) {

function pageInit(context) {

 const record = currentRecord.get()  // Get value of Membership Field   
 const user = runtime.getCurrentUser().name
}

var membership = currentRecord.getField({
    fieldId : "custentity1",
})

if(membership == "Elite"){
    //Setting up discount
    record.setValue({
        fieldId: "discountitem", //fieldId of the Discount Item 
        value: 137 // Internal ID of the Discount Item
    })}

    else {
        record.setValue({
            fieldId: "discount item",
            value: 0
        });
    }

    return {
        pageInit : pageInit
    }

});

retrieve multiple html values in javascript

On my node.js backend, I have this:

  {
    DATE: '2021-12-11 02:17:59.317432',
    LOCATION: 'Location',
    ASSIGNED_TRAINER: '[email protected]',
    CLIENT_USERNAME: 'Test User Name'
  },
  {
    DATE: '2022-01-04 02:27:11.278146',
    LOCATION: 'Location',
    ASSIGNED_TRAINER: '[email protected]',
    CLIENT_USERNAME: 'Test User Name'
  },
  {
    DATE: '2021-12-15 10:30:00.000000',
    LOCATION: 'Location',
    ASSIGNED_TRAINER: '[email protected]',
    CLIENT_USERNAME: 'Test User Name'
  }

and on the front-end, I am trying to grab the DATE field. and so what I do is this:

 <% if (data.length) {
    for(var i = 0; i < data.length; i++) { %>
      <input type="text" name="passedDates" id="passedDates" value="<%= data[i].DATE %>">
      <%  }
    } else { %>
   <% } %>

and then in my <script> tag, what I do is:

  for ( var z = 1; z <= lastDayOfM; z++ ) {
    
    const yourDate = new Date()
    var theDate = yourDate.toISOString().split('T')[0]

*here I am trying to get the values that I pass through the id ‘passedDates’

    var passedDates = document.getElementById("passedDates").value

    var finalDate = passedDates.split('-');

    var yyyy = finalDate[0];
    var mm = finalDate[1];
    var dd = finalDate[2];
    var theFinalDay = dd.split(' ')

but then I log yyyy, mm, dd, and then theFinalDay[0]. But it doesn’t store ALL of the date values in there. I need all of them in there, because then when going below:

    // check if todays date
    if ( z == today.getDate() && y == today.getFullYear() && m == today.getMonth() ) {
      var myTestPassedDate = theFinalDay[0]
      if (myTestPassedDate) {

*here i try to insert something into HTML, but it won’t do all 3 because it only stores one.

 day.innerHTML = myTestPassedDate + "<br><img src='https://miro.medium.com/max/512/1*nZ9VwHTLxAfNCuCjYAkajg.png' style='height: 10px; width: 10px;'>"
 

 }
      day.classList.add("today");
    }

    

how do I fix what I am trying to do? sorry if it is confusing, feel free to ask questions.

Creating 2D Array from an Array sorted by Atrribute | JavaScript

Hi i have this example:

let list = [{dog,1}, {dog,2}, {cat,1}, {cat,3}]

And i want this result:

let result= [
[{dog,1}, {cat,1}],
[{dog,2}],
[{cat,3}]]

I could do this with two different for-loops: first sorting by number, then creating a new array if the number changes in the second for-loop.
But i guess there will be a better solution but i’m not really familiar with JavaScript.

Maybe like .map() or .filter()?

How to open an “about:foo” URL, without being redirected to “about:blank#blocked”

I just want to set someones chrome home page to about:quit, so chrome always gets closed, once started. I tried to do that, but it didn’t even work to set this as home page.

So i tried, to set the URL to a data:text/html site, where you are redirected to about:quit per a javascript function, which gets called onload.
Doesn’t work either, because chrome just blocks redirecting to an about:foo URL.
How do I avoid that?

Catch block not executed when error is thrown from Try block within setTimeOut In Javascript

[![enter image description here][1]][1]I am trying to throw an exception from setTimeout within the try block.
See Below Code

    let a = 2 + 2;
    if (a == 4) {
        setTimeout(() => {
            console.log('Set time out')
            throw new Error()
        }, 3000)
    }
    else {
        console.log('Not 4')
    }

} catch (error) {
    console.log('catch block')
    console.log(error)
}```

But the control cannot come to the catch block and I am unable to see the result from console.log('catch block').


  [1]: https://i.stack.imgur.com/3DdhB.png