Vue component not loading in InertiaJS

I’m using InertiaJS to build a Vue3 / Laravel app. When I run my app in the browser it gives me the following error in the console. I’m new to InertiaJS and Vue3 and don’t know why my component doesn’t render.

Uncaught (in promise) TypeError: l is null

web.php

// Home route. 
Route::get('/', [HomeController::class, 'index'])

HomeController.php

public function index()
{
    return Inertia::render('Home');
}

My app.blade.php file which is located under ./resources/views/app.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>@yield('title') - Gainz</title>
        <meta 
        name="description" 
        content="@yield('description')">
        <meta name="google-site-verification" content="n5lVAknL3NblyWPmFzt3ARrtZbDDLIU-KOwA83NiO5w" />
        <!-- Roboto --> 
        <link rel="preconnect" href="https://fonts.gstatic.com">
        <link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,300;0,400;1,100;1,900&display=swap" rel="stylesheet"> 
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;0,800;1,300;1,400;1,500;1,600;1,700&display=swap" rel="stylesheet"> 
        <!-- CSS --> 
        <link rel="stylesheet" href="/css/main.css">

        <!-- Bootstrap --> 
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">

        <!-- Font Awesome --> 
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    
        <!-- Custom scripts --> 
        <script src="/js/app.js"></script>  
    </head>
    <body onmousedown="handleClick(event)">
        @inertia()
        @yield('scripts')
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" 
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    </body>
</html>

webpack.mix.js

const mix = require('laravel-mix');
const path = require('path')

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel applications. By default, we are compiling the CSS
 | file for the application as well as bundling up all the JS files.
 |
 */
mix .js('resources/js/app.js', 'public/js').vue()
    //.js('resources/js/track.js', 'public/js')
    //.js('resources/js/overview.js', 'public/js')
    //.js('resources/js/feed.js', 'public/js')
    .sass('resources/sass/main.scss', 'public/css');
// @ts-ignore
mix.webpackConfig({
    output: { chunkFilename: 'js/[name].js?id=[chunkhash]' },
    resolve: {
      alias: {
        '@': path.resolve('./resources/js'),
      },
      extensions: ['.js', '.vue', '.json'],
    },
    devServer: {
      allowedHosts: 'all',
    },
  });

app.js under ./resources/js/app.js

// @ts-nocheck
require('./bootstrap');
import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/inertia-vue3'
import { InertiaProgress } from '@inertiajs/progress'

// Creates the inertia vue app. 
createInertiaApp({
    resolve: (name) => require(`./Pages/${name}`),
    setup({ el, App, props, plugin }) {
        createApp({ render: () => h(App, props) })
            .use(plugin)
            .mount(el);
    },
});
// Progress bar. 
InertiaProgress.init()

Finally Home.vue under ./resources/js/Pages/Home.vue

<template>
  <div>Hello world</div>
</template>

JavaScript function returning undefined but both cases are defined

My function returns undefinded but the return value is defined.

function createcode() {
            var clientid = interaction.user.id;
            var sqlsearch = `SELECT COUNT(*) AS count FROM codes WHERE ClientID = '${clientid}'`
            database.query(sqlsearch, code, function(err, rows)  {
                if (err) throw err;
                var count = rows[0].count;
                if(count != 0)
                {
                    var exsitingcode;
                    var getexsitingcode = `SELECT codes, codes AS ecode FROM codes WHERE ClientID = '${clientid}'`;
                    database.query(getexsitingcode, async function(err, rows)  {
                        if (err) throw err;
                        exsitingcode = await rows[0].ecode;
                        console.log(`${interaction.user.username} tried creating a code but already has one: ${exsitingcode}`)
                        return exsitingcode;
                    })
                }
                else
                {
                    var code = Math.random().toString(36).slice(3);
                    var sql = `INSERT INTO codes(codes, ClientID) VALUES ('${code}', '${clientid}')`
                    database.query(sql, function(err)  {
                        if (err) throw err;
                        console.log(`Inserted Code: ${code}`)
                        setTimeout(() => {
                            var sqldelete = `DELETE FROM codes WHERE codes = '${code}'`
                            database.query(sqldelete, function (err) {
                                if (err) throw err;
                                console.log(`Code deleted: ${code}`);
                            })
                        }, 300000); // 5Min
                        console.log("returning code...")
                        return code;
                    })
                }
            })
        }

In both cases it returns undefinded. How can I bypass this?

using mysql & discord.js v13

Integrating socket.io with express is it a good idea?

I’m must say I’m very new to back end development,
I’m currently working on an exercise project of making a fake money poker website. I use Node.js socket.io/express-session/passport
At first, I mainly used express with a HTTP server listening on one port. Like this:

const express = require("express")
const app = express()

app.get('/home',connectEnsureLogin.ensureLoggedIn("/loginPage"),function(req, res) {

 //console.log(req.user.username+": sessionId: "+req.sessionID);
  return res.sendFile( __dirname+"/website/index.html"); 
} 
); 
const PORT = process.env.PORT || 5000; 
app.listen(PORT, () => console.log("Poker site Server started on ${PORT})")

The website wasn’t working very fast. When a client joined a poker table they needed to ask the server every second for new updates on the state of the game so that was a lot of HTTP requests coming into my server. So I decided without much theoretical certitude that it seemed like a good idea: To have the server use socket.io sockets to hand info for clients that are in poker tables, but when they are not in poker tables and are just browsing the site I use a HTTP server to handle their request. Code wise I feel I haven’t really managed to do this correctly. My code with Express, express-session, and passport combined makes sure only to hand information to users authenticated. But since The socket.io servers seem totally separate from all the express code, they don’t share the same authentication functionality as the express code. So I need to somehow link my express and socket.io code so I can check if a client is authenticated before handing him any info via sockets. here is the system I’m currently using I didn’t put all my code but I tried to summarize the essential parts:

const express = require('express');
const app = express();
//i creat the http server that is somehow linked with my express app when this server is listening
//it will call express handling methods.
const http = require('http').Server(app); 
const io = require('socket.io')(http);

const path = require("path");
const passport = require("passport");
const connectEnsureLogin = require('connect-ensure-login');
const AccountInfo = require("./AccountInfo").AcccountInfo;
const expressSession = require('express-session')({
    secret: process.env.SESSION_SECRET,
    resave: false, 
    saveUninitialized: false
  });

//passport setup
passport.use(AccountInfo.createStrategy()); 
passport.serializeUser(AccountInfo.serializeUser()); 
passport.deserializeUser(AccountInfo.deserializeUser());

//body parser
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

//Sessions
app.use(expressSession);

//!!!!here is where I connect socket.io with the sessions i found this in another forum. thanks to
//this code I can access the session that a client is using when their socket connects.
io.use(function(socket, next) {
  expressSession(socket.request, socket.request.res, next);
});

//so when a clients socket connects i save his socket.id to his session.
io.on('connection',function(socket) {
  console.log(`socket.io connected: ${socket.id}`);
  // save socket.io socket in the session
  socket.request.session.socketio = socket.id;
  socket.request.session.save();
});

//once the clients socket is connected directly after the clients sends a HTTP "PUT" request
//and this code answers it.
app.post('/Table/ConnectSocketToTable',Utilities.ensureLoggedIn(),function(req, res)
{
   
    //I retrieve the socket using the socket.id I had saved in the session. 
    let socket = io.sockets.sockets.get(req.session.socketio);

    let player = GetPlayerFromAnyTable(req.user.username);
    if(player==null)//the player can't be in two tables at once 
    {
//since now we are in an express callback, express made sure that the client is indeed
//authenticated with the middle-ware: "Utilities.ensureLoggedIn()" also just before I made sure
//the client is not in another table. So we are good to go we can now link the socket to the table
//and have the client receive all the info about the state of his table
        socket.join("table-"+req.session.passport.table);
        req.user.socket = socket;
        let table = GetTable(req.session.passport.table);
        table.sitPlayer(req.user);
    }
    else
    { 
//the player is already connected so we just update his socket to a new one
        player.requestUnseat=false;
        player.account.socket =io.sockets.sockets.get(req.session.socketio);
    }

    socket.on('chatMessage', function(data,time) {
        socket.to("table-"+req.session.passport.table).emit("chatMessage",req.user.username,data,time);
        console.log(`send chat message : ${data}`);
      });
    socket.on('disconnect', function() {
        GetTable(req.session.passport.table).requestUnsitUsername(req.user.username);
        console.log(req.user.username +" was disconnected so now requesting unsit");
      });

    console.log("the socket of "+req.user.username+" has being connected to table-"+req.session.passport.table);
    return res.sendStatus(200); 
});

So for me, the way I’m doing this seems pretty bad since “app.post(‘/Table/ConnectSocketToTable’…)” and “io.on(‘connection’,…)” are two different request listening functions I feel I should probably just do everything in one.
So should I do all the checks in the “io.on(‘connection’,…)” function and somehow manage to make sure the client is authenticated within the callback of io.on(‘connection’,callback) ?
or should I find a way to make the socket connection happen in the initial HTTP call the client uses to join a table, which is what I initially wanted?
But really I’m kinda lost because I’m telling myself maybe I don’t even need Express anymore and I should just use socket.io for everything. I seem to clearly lack the general understanding that would allow me to know what approach I should be going for so any help is welcome. I started doing this self-made exercise to get into server-side development but also if there is any other recommended exercise to start up with back-end development I’m definitely interested in hearing about it.

Removing specific Item/value from LocalStorage and updating the array

I’m struggling to edit an array stored in LocalStorage. I have prior functions that take the DIVs with their unique ID’s and add them as such: localStorage.setItem(“deleted_items”,JSON.stringify(items));

I then have a click function gets the id of the div and store it in a variable as with this example:

function getChat(input){
    let id = $(input).attr('id');
    console.log("Captured ID = " + id); //Returns 27615035196
}

From this, I then also store the items from LocalStorage in a variable

let hiddenItems = JSON.parse(localStorage.getItem("deleted_items"));

I then want to get the index of that item in the array:

const itemIndex = hiddenItems.indexOf();

And then finally with that index, splice the array to remove the item and update it again. But can’t seem to get the last piece of the puzzle here as my itemIndex is returning as -1

I can’t get the actual number of elements

I’m having a problem returning elements from my object array.

I have a slideshow in which an image (photo of the book) and a text (title of the book) must appear.

For the creation of the slideshow I have no problems because I am using querySelectors as shown in the code below.

The problem lies in showing the images with their titles.

In the first part of the code I have an array of objects that gives me the total number of elements present and based on this I create the slideshow (to create the scroll points and the “container” to contain the images) and then subsequently I call the function myFunction with id argument to return the single element (identified by an id).

What I notice is that the urls with the ids are returned to me, but the url with that id is returned multiple times (so it gets copied) and not just once as expected; I should have only 4 url ​​in total (each with the specific id of the element, since only 4 elements). The same happens when I return the array of objects, it does not return 4 but many more. (Below)

Referring to url1:

…/books/123456

…/books/123456

…/books/135623

…/books/123456

…/books/135623

…/books/123789

…/books/123456

…/books/135623

…/books/123789

…/books/146975

If I click on the arrows of the slideshow I only receive one image, the other images I do not receive.

I have no mistakes.

var slideIndex = 1;


    var outerXmlhttp = new XMLHttpRequest();
    var url = "https://wjko8t4509.execute-api.us-east-2.amazonaws.com/books";
    outerXmlhttp.onreadystatechange = function () {
      var innerXmlhttp;
      if (this.readyState == 4 && this.status == 200) {
        var allbook = JSON.parse(this.responseText);
        for (var i = 0, len = allbook.Items.length; i < len; i++) {
          id = allbook.Items[i].id
          document.querySelector('.slideshow-container').innerHTML += `
          <div class="mySlides fade">
            <div class="numbertext">${i+1}/${allbook.Items.length}</div>
            <img id="img" src onerror="this.onerror=null; this.src=myFunction(${id});" style="width:100%">
            <div class="text" id="title" onclick="myFunction(${id})"></div>
          </div>`;
          document.querySelector('#punt').innerHTML += `
          <span class="dot" onclick=currentSlide(${i+1})></span>`;
          showSlides(slideIndex);
          myFunction(id);
        }
      }
    };
    outerXmlhttp.open("GET", url, true);
    outerXmlhttp.send();

    function plusSlides(n) {
      showSlides(slideIndex += n);
    }

    function currentSlide(n) {
      showSlides(slideIndex = n);
    }

    function showSlides(n) {
      var i;
      var slides = document.getElementsByClassName("mySlides fade");
      var dots = document.getElementsByClassName("dot");
      if (n > slides.length) { slideIndex = 1 }
      if (n < 1) { slideIndex = slides.length }
      for (i = 0; i < slides.length; i++) {
        slides[i].style.display = "none";
      }
      for (i = 0; i < dots.length; i++) {
        dots[i].className = dots[i].className.replace(" active", "");
      }
      slides[slideIndex - 1].style.display = "block";
      dots[slideIndex - 1].className += " active";
    }

    function myFunction(id) {
      var url1 = "https://wjko8t4509.execute-api.us-east-2.amazonaws.com/books/" + id;
      innerXmlhttp = new XMLHttpRequest();
      innerXmlhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
          var myArr = JSON.parse(this.responseText);
          document.getElementById("img").src = "book_img/" + myArr.Item.immagine;
          document.getElementById("title").innerHTML = `<a href="fragmentProva.html?id=${id}">${myArr.Item.titolo}</a>`;
        }
      };
      innerXmlhttp.open("GET", url1, true);
      innerXmlhttp.send();
    }
<div class="slideshow-container" id="slideshow">
    <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
    <a class="next" onclick="plusSlides(1)">&#10095;</a>
  </div>

  <br>

  <div id="punt" style="text-align:center">
  </div>

Parse div and screenshot

I need to make a parser of promotional offers from the store’s website with the preservation of the design. I think it can be done with a screenshot of certain div’s, but how to implement it? Or if there is another way?

React onClick event working on twice clicks when clicking again

I am using react with typescript. I created one button and now I want to change it to invert its text on onClick event for that I am using useState to change the text of the button, for text inversion, I create one boolean flag.

If I click the button first it works perfectly and when I click again it. It won’t work on first click.

const Panel = () => {
    let flag: boolean = false;
    const [btnText, setBtnText] = useState("hello!");

    const changeBtnText = () => {
        if(!playButtonFlag){
            setBtnText("How are you!");
            flag = true;
        }
        else{
            setBtnText("hello!");
            flag = false;
        }
    }
  return <div>
      <Button name={btnText} onClick={changeBtnText}/>
  </div>;
};

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>