Nuxt JS use injected function from plugin in another plugin file

I’m using Nuxt JS’s inject function to inject a function into my page for code reusability. I’d like to use the function in another plugin file and can’t seem to get the function in there.

Here’s my set up:

  • plugins/utils/tracking.js
function setCookiePrefix () {
  return 'fudge__'
}

function getCookie (app, name) {
  try {
    const prefix = setCookiePrefix()
    const cookie = app.$cookies.get(`${prefix}${name}`)

    if (!cookie || cookie == '') {
      throw 'cookie not set'
    }

    return cookie
  } catch (err) { }

  return null
}

export default function ({ app, store, context }, inject) {

  /*
  * Get just the affiliate (cpm_id OR affiliate)
  * examples: "my_brand", "blah"
  */
  inject('getAffiliate', () => {
    const affiliate = getCookie(app, 'affiliate')
    const brand = getBrand(store)

    if (!affiliate) return brand

    return affiliate
  })

}

And the file I’m trying to utilise the getAffiliate function in from my tracking.js file:

  • plugins/init-brand.js
export default async function ({ app, route, store }) {
  const affiliate = app.$getAffiliate()
  console.log(affiliate) <-- undefined
}

I’ve tried:

  • app.$getAffiliate()
  • this.$getAffiliate() <– this works in a Vue file
  • $getAffiliate()
  • this.getAffiliate()

What am I missing to access my getAffiliate function in another plugin file?

Loosing useState Value on Refresh in React.js

I am sending an id from ProductListing Component and I am receiving that id using useParams in ProductDetail Component. In ProductDetail Component I am finding an object using find method and then I am setting it into singleProduct State. But on refresh I get singleProduct is undefined.

imports

import React, { useState, useEffect } from "react";
import { NavLink, useParams } from "react-router-dom";
import Loading from "../other/Loading";

state

const ProductDetail = () => {
  const [loading, setLoading] = useState(false);
  const [products, setProducts] = useState([]);
  const [singleProduct, setSingleProduct] = useState({});

receiving an id using useParams

  const { id } = useParams();

useEffect

  useEffect(() => {
   //GETTING PRODUCTS ARRAY
    getProductListingData();
   //FINDING A SINGLE OBJECT
    getProductID();
  }, []);

getting products array

const getProductListingData = async () => {
    try {
      const response = await fetch("http://localhost:8000/productListing");
      const data = await response.json();
      if (data) {
        setLoading(false);
        setProducts(data.products);
      } else {
        setProducts("PRODUCT LISTING DATA NOT FOUND");
      }
    } catch (error) {
      console.log(error);
    }
  };

  if (loading) {
    return <Loading loadingProductListing="Loading Product List" />;
  }

  const getProductID = () => {
    let foundProduct = {};
    foundProduct = products.find((item) => {
      return item.id === parseInt(id);
    });
    setSingleProduct(foundProduct);
  };

  // console.log("product ID = ", productID, typeof productID);
  console.log("products = ", products);
  console.log("singleproduct = ", singleProduct);

JSX

return (
    <>
      <div className="dvProducts col-12">
              <div className="row">
                <div className="col-12">
                  <NavLink
                    to="/product-listing"
                    className="text-dark mb-1 d-inline-block"
                  >
                    <i className="fa fa-angle-left f16"></i>
                    <span> Back</span>
                  </NavLink>
                </div>
                <div className="col-12 col-md-6 col-xl-4 mb-3">
                  <div className="border border-light shadow-sm p-1 h-100">
                    <div className="bg-light text-center p-5">
                      <a className="d-inline-block">
                        <img
                          src="images/description/coconut-water-200ml.png"
                          className="img-fluid"
                          alt="..."
                        />
                      </a>
                    </div>
                  </div>
                </div>
                <div className="col-12 col-md-6 col-xl-8 d-flex mb-3 mb-xl-0">
                  <div className="m-md-auto">
                    <div>
                      <h4>Coconut Water</h4>
                    </div>
                    <div className="mb-2">
                      <i className="fa fa-star text-warning d-inline-block"></i>
                      <i className="fa fa-star text-warning d-inline-block"></i>
                      <i className="fa fa-star text-warning d-inline-block"></i>
                      <i className="fa fa-star-o text-warning d-inline-block"></i>
                      <i className="fa fa-star-o text-warning d-inline-block"></i>
                    </div>
                    <div className="mb-3">
                      <p>
                        Every athlete's go to natural energy drink; Coconut
                        Water is a complete win-win for your everyday
                        rehydration needs. #iaminlovewiththecoco!
                      </p>
                    </div>
                    <div className="d-flex mb-3">
                      <div className="mr-2">
                        <h6 className="d-inline-block mb-1">Size:</h6>
                        <span className="d-inline-block">200ml</span>
                      </div>
                      <div className="mr-2 ml-2">
                        <h6 className="d-inline-block mb-1">Category:</h6>
                        <span className="d-inline-block">Juices</span>
                      </div>
                      <div className="ml-2">
                        <h6 className="d-inline-block mb-1">Price:</h6>
                        <span className="d-inline-block">
                          <i className="fa fa-inr"></i>
                          <span className="d-inline-block">40.00</span>
                        </span>
                      </div>
                    </div>
                    <div>
                      <button
                        className="btn btnSecondary"
                        href="detail.html"
                      >
                        Add to Bag
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
    </>
  );
};

export default ProductDetail;

How can I make a shape defined in SVG path d attribute to rotate?

I have this path M -13 11 A 17.81 17.81 0 0 0 14 11 L 41 30 A 50 50 0 0 1 -39 29 Z which is a shape like 1/4 of a circle that I want to make it rotate around the center.
So far what I tried was to compare the same shape rotated at 10 deg increments and see if any pattern emerges. I noticed that the values are incremented and decremented in relatively same quantities. At a 10 deg rotation they move about 2 points. But is not exact and when I tried to increment the values like that I got slightly distorted shape. Here same shape with 30 deg rotatian:
M -19 17 A 17.81 17.81 0 0 0 18.5 5 L 50 9 A 50 50 0 0 1 -57 47 Z

The nature of my project only allows me to use the d attribute to modify shapes. How can I rotate an SVG by only manpulating the path d attribute?

How can I mock the event argument in karma chai sinon mocha

How can I mock the event argument in karma chai sinon mocha ?

it('should have onmute event on tracks', async () => {
        if (fakeAudioTracks[0].onmute !== null) {
          console.log('before fakeAudioTracks[0] ', fakeAudioTracks[0]);

          eventCallbackSpy = Sinon.spy();
          subscriptions.events['track:mute'].set(subscription.listener.id, eventCallbackSpy);

          fakeAudioTracks[0].enabled = true;
          fakeAudioTracks[0].onmute(new Event('mute'));

          Sinon.assert.called(eventCallbackSpy);
          // expect(eventCallbackSpy.getCall(0).args[0].action).to.be.equal('muted');
          console.log('After fakeAudioTracks[0] ', fakeAudioTracks[0]);
          expect(eventCallbackSpy.getCall(0).args[0].action).to.be.equal('muted');
        }
      });

This is my test case, I want to pass an argument fakeAudioTracks[0] to fakeAudioTracks[0].onmute(new Event('mute')); this.

My onmute –

export function onmute(event: Event) : void {
  console.log('event ', event.target);
  const onmuteListeners: eventListeners = subscriptions.events['track:mute'];

  for (const entry of onmuteListeners) {
    const listener = entry[1];

    if (listener) {
      listener({
        action: 'muted' || 'unmuted', // need to check the event.target and return this.
        // action: event.target.enabled === 'true' ? 'muted' : 'unmuted',
        track: <MediaStreamTrack> event.target,
      });
    }
  }
}

auth.signOut() or signOut(auth). Is there any difference or major advantage with any of them?

Is there any difference or major advantage with using auth.signOut() or signOut(auth) of them?
This principle for sure also affects the same pattern for logging in, signing up, and so on.
The firebase documentation (Web9) only uses the approach with functions signOut(auth). But most articles or tutorials using auth.signOut().
I guess it’s a very basic question but I’ve seen everyone approaching it differently so I’m glad to solve this in the best way possible.

firebase.js

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";

const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: "",
};

const app = initializeApp(firebaseConfig);

export const auth = getAuth(app);
export default app;

Auth1.js

import { auth } from "./firebase.js";

// Option 1
function logout() {
  return auth.signOut();
}

Auth2.js

import { signOut } from "firebase/auth";
import { auth } from "./firebase.js";

// Option 2
function logout() {
  return signOut(auth);
}

How can I call API dynamically with button and depending on what user write in the input box in another page react?

How can I call API dynamically with button and depending on what user write in the input box in another page react.
Right now when I press submit I am receiving back the API Data which is what I expect and want to receive, however it doesn’t open it in another page.
in need to route the page in order to consumming the API in this page

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
import React, { useState } from "react";
import moment from "moment";
import { Link } from "react-router-dom";

const api = {
  base: "https://api.zrexpress.fr/tracking/",
};

function App() {
  const [query, setQuery] = useState("");
  const [tracks, setTrack] = useState([]);

  const search = (evt) => {
    console.log(`${api.base}${query}`);
    fetch(`${api.base}${query}`)
      .then((res) => res.json())
      .then((result) => {
        setTrack(result);
        setQuery("");
        console.log(result);
      });
  };
  const getDate = (date) => {
    var dateStringWithTime = moment(date).format("DD-MM-YYYY HH:mm:SS");
    return dateStringWithTime;
  };

  return (
    <div className="App">
      <div className="search-box">
        <input
          type="text"
          className="search-bar"
          placeholder="Code Tracking"
          onChange={(e) => setQuery(e.target.value)}
          value={query}
          onKeyPress={search}
          name="tracking"
        ></input>
        <Link to={(location) => `${api.base}${query}`}>
          <button onClick={search}>trackez</button>
        </Link>
      </div>
      <table className="table">
        <thead>
          <th>Date</th>
          <th>Situation</th>
        </thead>
        <tbody>
          <tr>
            <td className="date">
              {tracks.map((track) => (
                <p>{getDate(track.Date)}</p>
              ))}
            </td>
            <td className="Situation">
              {tracks.map((track) => (
                <p>{track.Situation}</p>
              ))}
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  );
}

export default App;

failed to load the tern package in atom

TypeError: Cannot read property ‘prototype’ of undefined
at extend (file:///C:/Users/INDIA/.atom/packages/Tern/lib/tern-view.coffee:1:1)
at file:///C:/Users/INDIA/.atom/packages/Tern/lib/tern-view.coffee:4:7
at Object. (file:///C:/Users/INDIA/.atom/packages/Tern/lib/tern-view.coffee:63:22)
at Object. (file:///C:/Users/INDIA/.atom/packages/Tern/lib/tern-view.coffee:1:1)
at Object. (file:///C:/Users/INDIA/.atom/packages/Tern/lib/tern-view.coffee:1:1)
at Module.get_Module._compile (C:UsersINDIAAppDataLocalatomapp-1.58.0resourcesappstatic<embedded>:11:149891)
at Object.value [as .coffee] (C:UsersINDIAAppDataLocalatomapp-1.58.0resourcesappstatic<embedded>:11:153485)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module._load (electron/js2c/asar.js:769:28)
at Module.require (file:///C:/Users/INDIA/AppData/Local/atom/app-1.58.0/resources/app.asar/static/index.js:72:46)
at require (C:UsersINDIAAppDataLocalatomapp-1.58.0resourcesappstatic<embedded>:11:149207)
at Object. (file:///C:/Users/INDIA/.atom/packages/Tern/lib/tern.coffee:1:12)
at Object. (file:///C:/Users/INDIA/.atom/packages/Tern/lib/tern.coffee:1:1)
at Object. (file:///C:/Users/INDIA/.atom/packages/Tern/lib/tern.coffee:1:1)
at Module.get_Module._compile (C:UsersINDIAAppDataLocalatomapp-1.58.0resourcesappstatic<embedded>:11:149891)
at Object.value [as .coffee] (C:UsersINDIAAppDataLocalatomapp-1.58.0resourcesappstatic<embedded>:11:153485)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module._load (electron/js2c/asar.js:769:28)
at Module.require (file:///C:/Users/INDIA/AppData/Local/atom/app-1.58.0/resources/app.asar/static/index.js:72:46)
at require (internal/modules/cjs/helpers.js:74:18)
at customRequire (C:UsersINDIAAppDataLocalatomapp-1.58.0resourcesappstatic<embedded>:1:802772)
at requireModule (C:UsersINDIAAppDataLocalatomapp-1.58.0resourcesappstatic<embedded>:14:1195622)
at Package.requireMainModule (C:UsersINDIAAppDataLocalatomapp-1.58.0resourcesappstatic<embedded>:11:3520513)
at C:UsersINDIAAppDataLocalatomapp-1.58.0resourcesappstatic<embedded>:11:3507053
at Package.measure (C:UsersINDIAAppDataLocalatomapp-1.58.0resourcesappstatic<embedded>:11:3505853)
at Package.load (C:UsersINDIAAppDataLocalatomapp-1.58.0resourcesappstatic<embedded>:11:3506626)
at PackageManager.loadAvailablePackage (C:UsersINDIAAppDataLocalatomapp-1.58.0resourcesappstatic<embedded>:11:384186)
at C:UsersINDIAAppDataLocalatomapp-1.58.0resourcesappstatic<embedded>:11:382609

Vue multiple options per loop

Trying to display multiple options in Vue2 for loop of a select.

Given an object with the structure;

{
    name: [
        'asc',
        'desc'
    ],
    price: [
        'cheapest',
        'expensive'
    ]
}

How to format the loop to get the output of;

<select>
    <option value="name:asc">name asc</option>
    <option value="name:desc">name desc</option>
    <option value="price:cheapest">name cheapest</option>
    <option value="price:expensive">name expensive</option>
</select>

Can’t work out the way to show the second option;

<select id="sortBy" class="form-control pr-3" v-model="sortBy">
    <option
        v-for="(options, sort) in sorting" :key="`${sort}`"
        v-bind:value="`${sort}:${options[0]}`"
    >
        {{ sort }} {{ options[0] }}
    </option>
</select>

How to calculate frequency of datetime field with javascript [duplicate]

I have an object which has information about execution of a job. This object have startDate and endDate fields as well.

let rawData: [
    {
        //other fields
        "startDate": 1643006221872,
        "endDate": 1643009367169,
    },
    {
        //other fields
        "startDate": 1643005533644,
        "endDate": 1643005734274,
    },
    {
        //other fields
        "startDate": 1643005927047,
        "endDate": 1643006079023, 
    } 
    // goes on...
    ]

I want to parse this object to another object(like table) like

exampleResult = [
    {"executionDate:": "24.01.2022", count:5},
    {"executionDate:": "23.01.2022", count:22},
    {"executionDate:": "22.01.2022", count:125},
    {"executionDate:": "21.01.2022", count:0},
    {"executionDate:": "20.01.2022", count:68},
]

I did this with several for loops but how can i do that with better performance and more clear way?

Edit: I am taking endDate as executionDate

Download an array as a CSV, but the data inside the array has commas in it

I have an array of arrays, which looks something like this:

rows = [
        [Name, Description, Number ...],
        ["A thing", "Description, but it has commas in it", 6, ...],
        ...
       ]

I am trying to download this as a csv file. Here’s the code I have so far:

// Make a csv from rows
let csv = rows.map(row => row.join(",")).join("n");

document.getElementById("csv_download").setAttribute("download", "file_name.csv");

document.getElementById("csv_download").href = "data:text/csv;charset=utf-8," + encodeURIComponent(csv);

This works fine when there are no commas inside the array, but right now it sees the comma after “Description” and splits it there. I also can’t split it by “, because some of the items are numbers.

How do I go about solving this?

construct a string from the words in array, starting with the 0th character [closed]

For arr = [“Daisy”, “Rose”, “Hyacinth”, “Poppy”], the output should be solution(arr) = DRHPaoyoisapsecpyiynth

First, we append all 0th characters and obtain string DRHP;
Then we append all 1st characters and obtain string DRHPaoyo
Then we append all 2nd characters and obtain string DRHPaoyoisap
Then we append all 3rd characters and obtain string DRHPaoyoisapaecp
Then we append all 4th characters and obtain string DRHPaoyoisapaecpyiy
Finally, only letters in the arr[2] are left, so we append the rest characters and get “DRHPaoyoisapaecpyiynth”;

Download a PDF file from an URL html [duplicate]

I am facing a problem downloading a PDF file from an URL in HTML, I am using download attribute and embedded pdf file from URL but cannot work. Because the client said must use PDF URL embedded in the download attribute. Below is my sample coding:

<a href="http://www.africau.edu/images/default/sample.pdf" download><button style="background-color: #e51b2a; color: white; border: none; height: 8%; border-radius: 8px;" type="button">Download</button></a>

I want the expected result is to click the download button and direct to download PDF from URL. Hope someone can guide me on how to solve the problem. Thanks.

Why does this website appear blank when viewing the map on a mobile phone, but it is normal when viewing it on a desktop?

I have developed a service website for finding bicycle rental stations, this is my practice work.

But when I encountered a strange situation, I shared this website to my friends on facebook and other social apps. Some friends responded that the map was blank when they opened it, but it was normal to view it on a computer. The computer can see the map normally!

Would you like to know what might be the cause? Thank you for watching my question. If you know the possible reason, please share with me. I will be very grateful for your help, thank you.

https://superawei.github.io/FINDBIKE/