Uncaught TypeError: _firebase__WEBPACK_IMPORTED_MODULE_0__.app.auth is not a function

ok so ive been building a discord clone with react redux, right now im stuck on the sign in page. it keeps giving me this error “Uncaught TypeError: firebase__WEBPACK_IMPORTED_MODULE_0_.app.auth is not a function” heres my code in firebase.js

import { initializeApp } from "firebase/app";
import { getDatabase } from 'firebase/database';
import { getAuth } from "firebase/auth"
import { GoogleAuthProvider } from "firebase/auth";


const firebaseConfig = {
  apiKey: "AIzaSyD0RxEfG1qZ4Qsoelw5E6J0rIaJSP4BbXQ",
  authDomain: "diacromb.firebaseapp.com",
  projectId: "diacromb",
  storageBucket: "diacromb.appspot.com",
  messagingSenderId: "237625612351",
  appId: "1:237625612351:web:2527b57f858d5a4688008a",
  measurementId: "G-3DEREK47Q2"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

const db = getDatabase(app);
const auth = getAuth();



const provider = new GoogleAuthProvider();

export {auth , app };
export {provider};
export default db;  

heres my code for Login.js

import { Button } from '@material-ui/core'
import {  auth, app } from './firebase'
import { provider } from './firebase'
import { signInWithPopup } from "firebase/auth"

import React from 'react'
import './Login.css'


function Login() {
   /* const signIn = () =>{
        const googleAuthProvider = new GoogleAuthProvider();
        app.auth().signInWithPopup(googleAuthProvider);    
       } */

        const signIn = ()=>{
            var google_provider = provider;
            
            app.auth().signInWithPopup(provider)
            .then((re)=>{
                console.log(re)
            })
            .catch((err)=>{
                console.log(err) 
            }) 
        }
    

    return (
        <div className='login'>
            <h2> I am the login page</h2>
            
          
            <Button onClick={signIn}>Sign In</Button>
        </div>
    );
    }



export default Login

I have no idea whats going on, ive read some other posts and people are saying to install older versions of firebase, I tried to do that and it still didnt work. Ive been stumped on this for nearly 2 days now

Unable to send strings with Axios using FormData using Vue.js

I’m trying to send an input of file along with an input of text in a single request using Axios and FormData in Vue.js. I’ve read that it is very simple, just do :

const formData = new FormData();
formData.append('file', file);
formData.append('text', text);
axios.post('ajax.php', formData)
.then(function (response){
    console.log(response.data);
})

But that only works for some absurd reason if “text” is an integer. This is the HTML code that I’m using for the form :

<div v-for="(gallery, i) in galleryMeta">
    <form @submit.prevent="editData('gallery', gallery.Id, i)">
        <div class="row no-gutters">
            <div class="col-xl-6 col-md-5 col-sm-4 col-12 pb-sm-0 pt-sm-0 d-flex align-items-center justify-content-md-start justify-content-sm-center">
                <div class="d-flex flex-column py-3 pl-sm-0 pl-4">
                    <h6 class="font-normal text-brand-primary pb-1 pl-md-0 pl-sm-4">Title:</h6>
                    <div class="d-flex justify-content-md-start justify-content-sm-center">
                        <input type="text" class="border-radius d-md-flex d-sm-none" v-model="gallery.Title">
                        <input type="text" class="border-radius w-75 d-md-none d-sm-flex d-none" v-model="gallery.Title">
                    </div>
                </div>
            </div>
            <div class="col-md-2 col-sm-3 col-12 pb-sm-0 d-flex align-items-center justify-content-sm-end justify-content-center">
                <div class="d-flex flex-sm-column pr-lg-0 pr-sm-3">
                    <label class="btn btn-brand-primary font-bold py-2 my-sm-0 my-2" for="file">EDIT</label>
                    <input type="file" id="file" ref="file" style="display: none;" accept="image/jpeg,image/png,image/webp" @change="pickData">
                    <button class="btn btn-brand-secondary font-bold px-lg-5 px-3 py-2 my-2 mx-sm-0 mx-2" @click="editData('gallery', gallery.Id, i)">UPLOAD</button>
                </div>
            </div>
        </div>
    </form>
</div>

The form works just fine for everything else. This is the Vue.js code :

let app = Vue.createApp({
    data: function(){
        return{
            File: '',
        }
    },
    methods:{
        pickData: function (){
            this.File = event.target.files[0];
        },
        editData: function (requestSection, Id, i, Title){
            if(requestSection === 'gallery'){
                const formData = new FormData();
                formData.append('file', this.File);
                formData.append('id', Id);
                formData.append('title', this.galleryMeta[i].Title);
                axios.post('ajax.php', formData, {
                    header: {
                        'Content-Type': 'multipart/form-data'
                    }
                }
                .then(function (response){
                    console.log(response.data);
            }
        }
    }
})

This is the ajax.php file to handle the Axios AJAX request :

<?php
$data = json_decode(file_get_contents("php://input"));
$request = $data->request;

if(isset($_FILES['file']['name'])){
    $id = json_decode($_POST['id']);
    $title = json_decode($_POST['title']);
    $file = file_get_contents($_FILES['file']['tmp_name']);
}
?>

You may’ve noticed the 2 first lines in the PHP code. The reason for why they’re there is that in the same PHP file I’m also handling other simple Axios POSTS requests by data binding, which all work properly. Although I believe that they do not cause any issues related to this, I’m including them just in case they do.

In the PHP file $id is defined properly, $file is defined properly however $title never is no matter what I do. After hours of intense troubleshooting, I’ve found that strings never make it past the Axios request, ever. If I change :

formData.append('title', this.galleryMeta[i].Title);

to

formData.append('title', '20');

It is immediately sent properly. The problem is not in the galleryMeta array of objects if I set the Title in galleryMeta to a random number everything works. All the variables that I’m using in the JavaScript code are properly defined. I tried to console.log() every single bit of that code, and all the variables contain their respective proper expected values, always. But strings never get parsed by Axios AJAX at all. It doesn’t matter how long the string is or what does it contain, it just won’t get past the request. I’ve also checked the values of that formData form with this loop :

for (var value of formData.values()) {
   console.log(value); 
}

And they’re all there, assigned properly, just like I wanted. So my question is pretty obvious. How the hell do I parse strings using FormData with Axios in Vue.js? What have I done wrong to make this happen? God, thank anybody who can point out the issue in this. Thank you!

Quickest solution to change landing page content based on a URL parameter

I’m looking to create a set of landing pages based on a common template based on the URL – for example – I’d like one “master” page which is /landing

Foe example if you navigate to: /electronics – the content would contain contain “Electronics” related content e.g. tags change, and swap out images and certain other containers.

For /magazines you’d do the same for “Magazines” based content.

I’m looking for an out of the box solution (e.g. service like Google Optimize, Hubspot, Unbounce etc) but would be using an entirely custom static landing page – I just want to avoid having to build the dynamic capability myself if necessary. Thoughts?

How to get average temperature depending of days for each month

I’m trying to get the temperature average by this operation : the total of temperature (for a month) dividing by the number of day that are in the month (if the month (xAxis variable) is present in the createdAt (of response variable)).

For example :
The number of day for November is (depending of response.createdAt) : 3
The number of day for December is (depending of response.createdAt) : 2

And then, use them for the operation.

I know that my explanation might be foggy, so don’t hesitate if you need more precision.

var response = [{
    "id": 294,
    "createdAt": "2021-12-08T00:00:00",
    "zipcode": "33000",
    "value": "{"Temperature":4.93,"Humidity":90}"
},{
    "id": 294,
    "createdAt": "2021-12-08T00:00:00",
    "zipcode": "33000",
    "value": "{"Temperature":7.93,"Humidity":90}"
},
{
    "id": 294,
    "createdAt": "2021-11-08T00:00:00",
    "zipcode": "33000",
    "value": "{"Temperature":44.93,"Humidity":90}"
},{
    "id": 294,
    "createdAt": "2021-11-08T00:00:00",
    "zipcode": "33000",
    "value": "{"Temperature":2.93,"Humidity":90}"
},
{
    "id": 294,
    "createdAt": "2021-11-08T00:00:00",
    "zipcode": "33000",
    "value": "{"Temperature":3.93,"Humidity":90}"
}];
var xAxis = ['10','11','12']; // contains months (representinf as integer)
var temperatureFinal = Array(xAxis.length).fill(null);

response.forEach(function(item){
  var dateData = moment(item.createdAt).format("MM");
  xAxis.forEach(function(value){
    if(dateData == value) temperatureFinal[xAxis.indexOf(value)]+= JSON.parse(item.value).Temperature;
  });
});

temperatureFinal.map(h=>console.log(h));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Input field value is not updating in React form

I am creating some input fields dynamically in react but once I update the value, it doesn’t update in the input field and show the previous value.

const Content = input => {
    const [inputList, setInputList] = useState({}); // it is initialized in other function with some dynamic keys:

        const getFiltersValues = (filters, papers) => {
              let list = {};
              for (const [key, values] of Object.entries(data)) {  
                  list[`${key}a`] = 0;
                  list[`${key}b`] = 0; // key is something like 'data size'
              }
              setInputList(list);
        };
        // setting up value like this:
        const handleChange = (e, field) => {
            const list = inputList;
        list[`${field}a`] = parseInt(e.target.value);
        setInputList(list);
    };
     
     // rendering input fields:
        return (
            <>
                 {filters && filters.length > 0 && (
                                    <div>
                                        {filters.map(f => {
                                            return (
                                                <div>
                                             // correct updated value is shown on the console but its not updated in the 'value' attribute
                                                  {console.log(inputList[`${f.value}a`])}
                                                   <input
                                                   value={inputList[`${f.value}a`] || 0}
                                                   type="number"
                                                   onChange={e => handleChange(e, f.value)}
                                                 />
                                                    </div>
                                                </div>
                                            );
                                        })}
                                    </div>
                                )}
            </>
    );
    
};

Any suggestions/hints where I am getting wrong? Thank you.

How to use either this type or another based on props only? React Typescript Discriminating Unions

I have a componenet:

type Base = {
    color: string
}

type Button = {
    to: string
} & Base

type Link = {
    link: string
    linkNewTab: boolean
} & Base

type ComponentProps = Button | Link 

export const Button: React.FC<ComponentProps> = (props) => {
    return (<>
        {props.link ? <Link newTab={props.linkNewTab}>...</Link> : props.to && <Button>...</Button>}
    </>)
}
  • There is a base type with props which both types have in common.
  • The Component should either has Button or Link type based on the given props. But if it has Link, these props are preferred.

Typescript Error:

Property 'link' does not exist on type 'PropsWithChildren<ComponentProps>'.
  Property 'link' does not exist on type '{ to: string; } & Base & { children?: ReactNode; }'.ts(2339)

What I don’t want:

  • I can solve the problem by adding a type to the Base type and decide from their which props are allowed. I would like to automatically decide that based on props.

Information: 4.5.4 TypeScript Version

Use scrollHeight to scroll to the bottom, but doesn’t work for div

I want to make the div always scroll to the bottom of the content, however, I fail to do that, but my solution works for textarea. I don’t know why.

I have the following code:

Use textarea:

var i = 0;
var txt = 'Stack Overflow is a question and answer website for professional and enthusiast programmers. It is the flagship site of the Stack Exchange Network,[4][5][6] created in 2008 by Jeff Atwood and Joel Spolsky.[7][8] It features questions and answers on a wide range of topics in computer programming.[9][10][11] It was created to be a more open alternative to earlier question and answer websites such as Experts-Exchange. Stack Overflow was sold to Prosus, a Netherlands-based consumer internet conglomerate, on 2 June 2021 for $1.8 billion.[12]'
function type(){
  if (i < txt.length) {
    document.querySelector('textarea').scrollTop =  document.querySelector('textarea').scrollHeight
    document.querySelector('textarea').innerHTML += txt.charAt(i);
    i++;
    setTimeout(type,1)
  }
  }
  type()
<textarea ></textarea>

Use div:

var i = 0;
var txt = 'Stack Overflow is a question and answer website for professional and enthusiast programmers. It is the flagship site of the Stack Exchange Network,[4][5][6] created in 2008 by Jeff Atwood and Joel Spolsky.[7][8] It features questions and answers on a wide range of topics in computer programming.[9][10][11] It was created to be a more open alternative to earlier question and answer websites such as Experts-Exchange. Stack Overflow was sold to Prosus, a Netherlands-based consumer internet conglomerate, on 2 June 2021 for $1.8 billion.[12]'
function type(){
if (i < txt.length) {
    document.querySelector('div').scrollTop =  document.querySelector('div').scrollHeight
    document.querySelector('div').innerHTML += txt.charAt(i);
    i++;
    setTimeout(type,1)
  }
  }
  type()
div{
width:100px;
height:100px;
}
<div></div>

I find that if use textarea instead of using div, the scrollTop = scrollHeight will work and will always scroll to the bottom, but if I use div, it won’t work.

Could anyone explain to me why this doesn’t work?

Thanks for any responds!

Hardhat – get latest block number in seconds

How to get the latest block number in seconds (TEST_URL = RPC BSC test) :

const provider = new ethers.providers.JsonRpcProvider(Process.env.TEST_URL);
let timestamp = 0;
// Block Number
provider.getBlockNumber().then(function(blockNumber) {
    timestamp = blockNumber;
});

JAVASCRIPT Modules Access-Control-Allow-Origin Error in Safari [duplicate]

I am not exactly new to javascript but I keep encountering errors when I try to use modules. Here is a snapshot of my html:

<script type= "module" src="scopes.js"></script>
<script type="module" src = "testImport.js" ></script>

Essentially, what I am trying to do is export class in scopes.js as default and then import it in testImport.js. The javascript snapshots:

1.

   constructor(src, type) {
       this.src = src;
       this.type = type;
      this.img = document.createElement('img');
   } 
   ///more stuff below of course
import {Scope} from './scopes.js'

When I try to run my html file, I get the errors:

[Error] Origin null is not allowed by Access-Control-Allow-Origin.
[Error] Failed to load resource: Origin null is not allowed by Access-Control-Allow-Origin. (scopes.js)

I know this has something to do with security and the browser but I am really stuck on this because I thought safari supports modules. I am using safari 15.2.

Thank you in advance to everyone that reads this and answers!

Override JavaScript global native Object() constructor

I’m trying to override Object() calls in JavaScript, in order to intercept and save all the parameters passed to the object constructor.

I don’t have any access to the original code since I am running from an injected code but I do run from the same scope and share the same window of the original code.

I tried this approach:

(function (nativeObject) {
    window.Object = function (value) {
        if (value.magic) {
            window.myMagic = value.magic;
        }
        return nativeObject(value);
    }
})(Object);

as well as saving the original window.Object on window.nativeObject and calling it from within my hook, but in both ways I end up getting:

TypeError: Object.defineProperty is not a function
TypeError: Object.keys is not a function
Uncaught (in promise) TypeError: Object.isExtensible is not a function
Uncaught (in promise) TypeError: Object.create is not a function

Is it because my window.myMagic calls the the Object methods to set the myMagic key in the window object?

Is what I’m trying to do possible?

How do I persuade babel to let me define a Javascript array of consts?

I’m building my first expo/react app. I keep getting an “Unexpected token” error message in App.js:

export default class App extends React.Component {
   const [message, setMessage] = useState("...");

the error being in the [ of the line beginning const.

As best I can tell, this is a babel issue: this syntax was introduced in ES2015. AFAICS, this should be resolvable by adding @babel/preset-env to babel.config.js thus:

module.exports = function(api) {
  api.cache(true);
  return {
      presets: [
          '@babel/react',
          '@babel/env',
      ],
      plugins: [
          '@babel/proposal-class-properties',
      ],
  };
};

Bundling succeeds, but the error remains! What am I missing?

How can I show a modal using an animation with Tailwind and react.js?

I am trying when I click on a modal to have an animation to show the modal but I don’t achieve to do that using Tailwind and react.

Here is my code :

import React, { useState, useCallback } from "react";
import ReactDOM from "react-dom";
import Wrapper from "./Wrapper";
import Input from "./Input";

import "./styles.css";
import Button from "./Button";
import Modal from "./Modal";

function App() {
  const [showModal, setShowModal] = useState(false);
  const handleShowModal = useCallback(() => {
    setShowModal(!showModal);
  }, [showModal]);
  const handleCloseModal = useCallback(() => {
    setShowModal(false);
  }, []);
  return (
    <div className="p-4">
      <h1 className="text-red-500 text-center">PlayGround</h1>
      <Wrapper className="p-2">
        <Input />
      </Wrapper>
      <Wrapper className="p-2">
        <Button onClick={handleShowModal}>Show Modal</Button>
        {showModal && <Modal onCancel={handleCloseModal} />}
      </Wrapper>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

And you can see my full code here :

my full project

I would like something like that :

the goal

How can I do that ?

Thank you very much !

can someone help me please with some Javascript problem

Im very new with javascript and been a little difficult I have a challenge to solve and i tried so many different methods but cant figure it out this is the steps for the challenge I would apreciate some help. thanks


Declare a variable named maxNumber and use a Math method to assign it the largest number from the following numbers: 7, 4, 8, 11, 5, 2
Log the value of maxNumber to the console.
Declare a variable named randomNumber and assign it an expression using the following Math.floor, Math.random and the variable maxNumber so that it outputs a random number between 0 and 10