Categories
JavaScript Answers

How to convert timestamp to relative time with JavaScript?

Sometimes, we want to convert timestamp to relative time with JavaScript.

In this article, we’ll look at how to convert timestamp to relative time with JavaScript.

How to convert timestamp to relative time with JavaScript?

To convert timestamp to relative time with JavaScript, we use the Intl.RelativeTimeFormat constructor.

For instance, we write

const units = [
  ["year", 31536000000],
  ["month", 2628000000],
  ["day", 86400000],
  ["hour", 3600000],
  ["minute", 60000],
  ["second", 1000],
];

const rtf = new Intl.RelativeTimeFormat("en", { style: "narrow" });
const relatime = (elapsed) => {
  for (const [unit, amount] of units) {
    if (Math.abs(elapsed) > amount || unit === "second") {
      return rtf.format(Math.round(elapsed / amount), unit);
    }
  }
};

to create the rtf RelativeTimeFormat object.

Then we define the relatime function that takes the elapsed relative in milliseconds.

And then we use a for-of loop to loop through the units array.

In the loop, we check if the absolute elapsed amount is bigger than amount or the unit is 'second'.

If either are true, then we return the formatted elapsed time we get with rtf.format to format the elapsed time to the unit.

Conclusion

To convert timestamp to relative time with JavaScript, we use the Intl.RelativeTimeFormat constructor.

Categories
JavaScript Answers

How to find element index in container with JavaScript?

Sometimes, we want to find element index in container with JavaScript.

In this article, we’ll look at how to find element index in container with JavaScript.

How to find element index in container with JavaScript?

To find element index in container with JavaScript, we can use the spread operator and the indexOf method.

For instance, we write

const index = [...el.parentElement.children].indexOf(el);

to use el.parentElement.children to get all the child elements of the el element’s parent element.

Then we spread the node list to an array.

Next, we call indexOf with el to get the index of el in the array of elements.

Conclusion

To find element index in container with JavaScript, we can use the spread operator and the indexOf method.

Categories
JavaScript Answers

How to wait until page is completely loaded with Puppeteer and JavaScript?

Sometimes, we want to wait until page is completely loaded with Puppeteer and JavaScript.

In this article, we’ll look at how to wait until page is completely loaded with Puppeteer and JavaScript.

How to wait until page is completely loaded with Puppeteer and JavaScript?

To wait until page is completely loaded with Puppeteer and JavaScript, we call goto with an object with the waitUntil property.

For instance, we write

await page.goto(url, { waitUntil: "domcontentloaded" });

to call page.goto with the url and { waitUntil: "domcontentloaded" } to navigate to the url and wait until the whole page is loaded by setting waitUntil to 'domcontentloaded'.

Conclusion

To wait until page is completely loaded with Puppeteer and JavaScript, we call goto with an object with the waitUntil property.

Categories
JavaScript Answers

How to do list comprehensions like Python with JavaScript?

Sometimes, we want to do list comprehensions like Python with JavaScript.

In this article, we’ll look at how to do list comprehensions like Python with JavaScript.

How to do list comprehensions like Python with JavaScript?

To do list comprehensions like Python with JavaScript, we can use the array filter method.

For instance, we write

const string = "1234-5";
const forbidden = "-";

console.log(
  [...string].filter((c) => !forbidden.includes(c)).map((c) => parseInt(c))
);

to call filter with an array with the characters in string to return a new array with the characters that aren’t in the forbidden string.

We call map with a callback to convert each value to an int with parseInt.

Conclusion

To do list comprehensions like Python with JavaScript, we can use the array filter method.

Categories
React Answers

How to maintain state after a page refresh in React?

Sometimes, we want to maintain state after a page refresh in React.

In this article, we’ll look at how to maintain state after a page refresh in React.

How to maintain state after a page refresh in React?

To maintain state after a page refresh in React, we can save the state in session storage.

For instance, we write

const Comp = () => {
  const [count, setCount] = useState(1);

  useEffect(() => {
    setCount(JSON.parse(window.sessionStorage.getItem("count")));
  }, []);

  useEffect(() => {
    window.sessionStorage.setItem("count", count);
  }, [count]);

  return (
    <div className="App">
      <h1>Count: {count}</h1>
      <button onClick={() => setCount(count + 1)}>+</button>
    </div>
  );
};

to save the latest value of count to session storage with sessionStorage.setItem.

We watch the value of count and call sessionStorage.setItem whenever it changes with the useEffect hook.

To get the item after it refreshes, we call sessionStorage.getItem in the first useEffect callback, which is called with an empty array so it’s run only when the component first mounts.

Conclusion

To maintain state after a page refresh in React, we can save the state in session storage.