Issue with Connecting to Firebase Datastore

I’m trying to create a list of users using the collection feature in firebase however, I am running into these errors.
Errors when trying to submit data
Here is the information that I am entering.

Input field

Here is my code.

const Signup = () => {
   const [err, setErr] = useState(false);
   const handleSubmit = async (e) => {
      e.preventDefault(); // prevents page reload

      const displayName = e.target[0].value;
      const email = e.target[1].value;
      const password = e.target[2].value;
      const profilePic = e.target[3].files[0];

      try {
         const res = createUserWithEmailAndPassword(auth, email, password);

         const storageRef = ref(storage, displayName);

         const uploadTask = uploadBytesResumable(storageRef, profilePic);

         uploadTask.on(
            (error) => {
               setErr(true);
            },
            () => {
               getDownloadURL(uploadTask.snapshot.ref).then(
                  async (downloadURL) => {
                     await updateProfile(res.user, {
                        displayName,
                        photoURL: downloadURL,
                     });

                     await setDoc(doc(db, "users", res.user.uid), {
                        uid: res.user.uid,
                        displayName,
                        email,
                        photoURL: downloadURL,
                     });
                  }
               );
            }
         );
      } catch (err) {
         setErr(true);
      }
   };

Authentication works perfectly. I just have a problem creating a collection in the cloud firestore.

submit with javascript inside a foreach php

I submit a form without refresh. It is working alone but inside foreach (php) it doesen’t insert data and from the second onwards it doesn’t work.
Only with php works very well, but with javascript nothing is done

I what did I do OR what I need to do?
The image shows whats happens
enter image description here

named id form with (myform + id(x,y,z) and fetch in javascript did the same.

<script>
    const myForm = document.getElementById('follow<? echo $card['user_id']; ?>');

    myForm.addEventListener('submit', function(e){
        e.preventDefault();

        const formData = new FormData(this);

        fetch('../config/follow.php', {
            method: 'post',
            body: formData
        }).then(function(response){
            return response.text();
        }).then(function(text){
            //alert(text);
                $("#updater").load(window.location.href + " #update" ); //here update my div or buttom (its working for me)           
        }).catch(function(error){
            alert(error);
        });
    });
</script>
<form method="POST" id="follow<? echo $card['user_id']; ?>">

inputsss

<div id="update">
<!--here update after submit-->
<button type="submit" name="unfollow" class="btn-success"></button>
<button type="submit" name="follow" class="btn-secondary"></button>
</div>
</form>

Javascript rename object key, but keep the order

I want to make a edit button, where you can edit the name of an item. However it should be in the right order, because if it does not, the UI would be in the false order. For example when you’re edit the name of the first item, it rotates to the end. How can I fix that ?

dict:{
math: [],
english:[],
french:[]
}

If I do rename math with :

sport = math
delete Object.assign(math, sport);

It takes this order:

    dict:{
english:[],
french:[],
sport:[]
}

How can I fix that ?

Why am I getting an error when clicking button only when hook is being called?

It looks like anytime I call a hook inside the .then() in ApiClient.get, I get this error:

Uncaught TypeError: Cannot read properties of undefined (reading 'logout')

Whenever setRolesAndPermissions(res.data); is commented out, the Logout functionality works as intended. However, when it’s uncommented – it throws the aforementioned error in the console.

This feels like it’s a timing issue and I’ve tried many many ways to fix this but to no avail, I’ve completely ran out of options.

Why’s this happening and how can I fix it?

export default function App({ appData }) {
        let parsedAppData = JSON.parse(appData);
        const [rolesAndPermissions, setRolesAndPermissions] = useState(null);
    
        useEffect(() => {
            initKeyCloak();
        }, [])
    
        const keycloak = new Keycloak({
            url: parsedAppData['keycloakUrl'],
            realm: parsedAppData['keycloakRealm'],
            clientId: parsedAppData['keyCloakClientId'],
            redirectUri: parsedAppData['keyCloakRedirectUri'] 
        });
    
        const initKeyCloak = () => {
            keycloak.init({
                onLoad: 'login-required',
                redirectUri: parsedAppData['keyCloakRedirectUri'] 
            }).then(afterLogin).catch(onError);
        };
    
        const afterLogin = () => {
            let cancelSource = cancelTokenSource();
    
            const headers = {
                'Accept': 'application/json',
                'Authorization' : `Bearer ${keycloak.token}`
            };
    
            ApiClient.get('/getLoggedInUserPermissions', {headers})
                .then(res => {
                    console.log(res);
                    setRolesAndPermissions(res.data);
                }).catch(err => {
                console.log(err);
            });
    
            return function cleanup() {cancelSource.cancel();};
        }
        const onError = (error) => {
            console.login('afterLogin');
        }
    
        return (
            <>
                <button type="button" onClick={() => keycloak && keycloak.logout()}>Logout</button>
            </>
        );
    
    }

How to resize widget in gridstack to our custom gs-width, gs-x, gs-min-width, gs-max-width?

Iam have tried to resize my widget to decimal points like 1.5, 2.5. But, gridstack does not supports the decimal points in grid-stack-item[data-gs-x], grid-stack-item[data-gs-width], grid-stack-item[data-gs-min-width], grid-stack-item[data-gs-max-width].
The supported points by default is 1,2,3,4,5,6,7,8,9,10,11,12. I need to resize the widget to 1.5. So, I have added the following css changes in the https://cdnjs.cloudflare.com/ajax/libs/gridstack.js/0.2.4/gridstack.min.css source, which I have downloaded and using it. The changes I have made is

    .grid-stack>.grid-stack-item[gs-w="1.5"] {
    width: 12.49999999995%
}

.grid-stack>.grid-stack-item[gs-x="1.5"] {
    left: 12.49999999995%
}

.grid-stack>.grid-stack-item[gs-min-w="1.5"] {
    min-width: 12.49999999995%
}

.grid-stack>.grid-stack-item[gs-max-w="1.5"] {
    max-width: 12.49999999995%
}

But, after adding these no effect, I cannot resize to 1.5 widget size. Kindly help, Thanks.

Also, I tried in the jsFiddle too, https://jsfiddle.net/frjq7m4x/8/

Html

<h1>gridstack.js base demo for issues</h1>
<p>Fork and modify me to demonstrate your issue when creating an issue for gridstack.js</p>
<div><a class="btn btn-default" onClick="addNewWidget()" href="#">Add Widget</a></div>
<br />

<div class="grid-stack"></div>

JavaScript

var options = { // put in gridstack options here
  disableOneColumnMode: true, // for jfiddle small window size
  float: false
};
var grid = GridStack.init(options);

var count = 0;
var items = [
    {x: 0, y: 0, w: 2, h: 2},
    {x: 2, y: 0, w: 2},
  {x: 3, y: 1, h: 2},
  {x: 0, y: 2, w: 2},
];

addNewWidget = function () {
  var node = items[count] || {
    x: Math.round(12 * Math.random()),
    y: Math.round(5 * Math.random()),
    w: Math.round(1 + 3 * Math.random()),
    h: Math.round(1 + 3 * Math.random())
  };
  node.content = String(count++);
  grid.addWidget(node);
  return false;
};

addNewWidget();
addNewWidget();

Css

.grid-stack {
  background: lightgoldenrodyellow;
}

.grid-stack-item-content {
  color: #2c3e50;
  text-align: center;
  background-color: #18bc9c;
}

and gridstack css from the cdn downloaded

aws-sdk v3 dynamodb: binary data cannot be validated by joi anymore

I have binary data stored in DynamoDB.
With aws-sdk v2 for javascript the binary data is returned in a format like this:

<Buffer 1b 85 23 00 2c 07 6c 63 12 d9 c7 ec 24 ea 89 ....

This can be validated by Joi using joi.binary(). Without updating my data in DynamoDB, using aws-sdk v3 my data looks like this when retrieved:

Uint8Array(1624) [
27, 133,  35,   0,  44,   7, 108,  99,  18, 217, 199, 236, ....

The rest of the application can handle the data without a problem only joi is not recognizing the data as binary anymore. I have tried to change the encoding setting in joi e.g. (Joi.binary().encoding('base64');) but I’m not sure what the correct one is.

How do I need to set my joi schema to make it work with the different data format?

How to manage a state from one slice within a different slice in redux toolkit? Or best practice for a “parent-slice”?

i am developing a webapp with the MERN-Stack and redux toolkit as a practice.

Now i have a big problem. I want to have one “parent-slice” (i call it general slice) and want to put there in the initialstate the “base”-functions of my entire app. For example, isLoading, showSideBar, language and so on. So the states, that i need everywhere.

So, that everytime, when i am in a different slice (userslice, taskslice, textslice, etc.) i can access and change “base-functions” of my app.

One example is the isLoading:
I want the the isLoading turned to true, when i am fetching data from my database, so my Loading-component with a spinner can be returned and the isLoading should be turn to false, when the data is there or the request was rejected.

Here an example with the registerUser function.

.addCase(registerUser.pending, (state) => {
        isLoadingTrue();
      })
      .addCase(registerUser.fulfilled, (state, { payload }) => {
        const { userData } = payload;
        isLoadingFalse();
        state.userData = userData;
      })
      .addCase(registerUser.rejected, (state, { payload }) => {
        isLoadingFalse();
      })

First i had the state of isLoading in my userslice and everything worked with state.isLoading = true/false.

But now, when i want a lot more slices like task, text and so on. I think its really bad, to put the isLoading in every different slice! Especially because i have a shared layout, with a protected route-component. There is the loading component returned, when isLoading === true.

if (user.isLoading) {
   return <Loading center />;}

So i would need to import every store, from every functional slice and would have to work with || statements.

I searched for a solution how to access a state from one slice, within another slice. They all looked very very complicated, and a lot of code for a thing, that i would need to implement a lot, in almost every slice.

So is there a possibility or another option to have access to one base-state where all the different slice could access to and change the states easily? Or do you can declare a “parent-store” in your store.js or something like that?

Or how you solve it in production? Or how do you organize your code?

Thanks for help.

Edit: i still tried to use reducers in the general slice. But i cant invoke them in different slices, because i cant use (useDispatch) there.
Also i read, that it is bad practice, to try to manipulate states from different slices within one slice.

Javascript file operations

Hello i need to add 2 properties to the below codes, but i don’t know how to do. I will be glad if you help me thank you:

1- Empty lines will not be inserted
2- Extra spaces in textarea will be deleted (max 1 space)

https://jsfiddle.net/m8p64nby/

 <div name="mainForm" id="Main">
    
          <p>
            <div>
              <label for="file">Choose file to upload</label>
              <input type="file" id='fileinput' accept=".txt">
            </div>
  </div>

(function() {
  var input = document.getElementById("fileinput");
  input.addEventListener("change", loadFile, false);

  function loadFile() {
    var file, fr;

    if (typeof window.FileReader !== 'function') {
      alert("The file API isn't supported on this browser yet.");
      return;
    }

    if (!input.files) {
      alert("This browser doesn't seem to support the `files` property of file inputs.");
    } else if (!input.files[0]) {
      alert("Please select a file before clicking 'Load'");
    } else {
      file = input.files[0];
      fr = new FileReader();
      fr.onload = receivedText;
      fr.readAsText(file);
    }

   function receivedText() {
  var data = fr.result.split('n');
  for(let i = 0; i < data.length; i++) {
    let app = document.querySelector('#Main');
    let html = `<p>input ${i}:<textarea id="input1" cols="20" rows="2">${data[i]}</textarea></p>`;
    app.insertAdjacentHTML("beforebegin", html);
  }
}
  }
})();

I will be glad if you help me thank you:

Updating HTML table using JS

I am trying to update a table in my HTML to diplay the first name of users the dependent. I’ve console logged everything and all the values are correct but I get an error saying “Uncaught TypeError: Cannot set properties of null” but none of my vaules are showing null.

In the example below, numberOfDependentsInput = 1.

const numberOfDependentsInput = 1;
for (let i = 0; i < numberOfDependentsInput; i++) {
  const dependentFirstNameInput = document.getElementById(`dependentFirstName-${i}`);
  const dependentFirstName = dependentFirstNameInput.value;
  console.log(dependentFirstName);
  console.log(numberOfDependentsInput);
  console.log(i);
  console.log(`dependentFirstName-${i}`);
  const tdElement = document.getElementById(`dependentFirstName-${i}`).nextElementSibling;
  tdElement.textContent = dependentFirstName;
}
<div class="form-group" id="getWhichDependentsTraveled">
  <label for="whichDependentsTraveled">Which of your dependents traveled with you?</label>
  <table id="dependentsTravelTable">
    <tbody>
      <tr>
        <td><input type="checkbox" id="dependent0" name="dependent0"></td>
        <td id="dependentFirstName-0">Dependent 1</td>
        <td><input type="checkbox" id="dependent1" name="dependent1"></td>
        <td id="dependentFirstName-1">Dependent 2</td>
      </tr>
      <tr>
        <td><input type="checkbox" id="dependent3" name="dependent3"></td>
        <td>Dependent 3</td>
        <td><input type="checkbox" id="dependent4" name="dependent4"></td>
        <td>Dependent 4</td>
      </tr>
    </tbody>
  </table>
</div>

I’ve tried using innerHTML but I get the same error. I just need to know who I can update the “Dependent 1” string in the HTML with a variable.

Is it possible to make websites without using html (in python/js)?

I code websites from time to time, sometimes using python and sometimes js. I recently started working on a project that can be used to make websites, style them and add logic using a programming language i am making (basically html, css and js all in one) and that git me thinking if there is there any way to already to this using packages in existing language. So just out of curiosity, is there a way to code websites using only python/js? If there is can you please state the names of the packages used to do so and show me some examples? Thanks in advance

I have been trying to to use js to integrate a gui into a html code, but that still requires html

Is there a lightweight way to scan a static path for files from a chrome or firefox extension?

I’m trying to implement a chrome or firefox extension, that basicly scans a static path on my hard drive for a file matching content from the matched html page. I know about File System Access API, but it’s unconvenient for this use-case, since i don’t see how someone can be asked for the directory only once.
I know that direct filesystem access is basically impossible (unless i want to use my browser with security features disabled or some other risky hacks).
I know it would be possible, if i setup a database with a web-app as an interface.
However, i think building something like a webserver, that serves as an interface to a database that is somehow updated with the file metadata is somewhat overengineered. I would consider it, if i could implement a lightweight solution, however i’m a windows user and i don’t want to setup a whole xampp or dedicated raspberry system.

I’m open for any ideas.

Generating legends for vega lite visualisation

I am able to implement vega-lite chart which renders as follows:

enter image description here

The code for it looks something like this:

{
  "width": 400,
  "config": {"view": {"continuousWidth": 600, "continuousHeight": 300}},
  "data": {"name": "data-eb6aa7311f370dcc2f64d37c32c9e387"},
  "usermeta": {"embedOptions": {"renderer": "svg"}},
  "layer":[
    {
      "mark": {"type": "bar", "width": {"band": 0.2}},
      "encoding": {
        "x": {"field": "title", 
              "type": "nominal",
              "axis": { "title": "Quizzes"}
             },
        "y": {"field": "my-score", 
              "type": "quantitative",
              "axis": { "title": "Percentage Score"}
             }
      }
    },
    {
      "mark": {"type": "line", "color": "red"},
      "encoding": {
        "x": {"field": "title", "type": "nominal"},
        "y": {"field": "max", "type": "quantitative"}
      }
    },
    {
      "mark": {"type": "circle", "color": "red", "size":100, "opacity": "100"},
      "encoding": {
        "x": {"field": "title", "type": "nominal"},
        "y": {"field": "max", "type": "quantitative"},
      }
    },
    {
      "mark": {"type": "line", "color": "#02c754"},
      "encoding": {
        "x": {"field": "title", "type": "nominal"},
        "y": {"field": "avg", "type": "quantitative"}
      }
    },
    {
      "mark": {"type": "circle", "color": "#02c754", "size":100, "opacity": "100"},
      "encoding": {
        "x": {"field": "title", "type": "nominal"},
        "y": {"field": "avg", "type": "quantitative"}
      }
    },
    {
      "mark": {"type": "line", "color": "#02b6de"},
      "encoding": {
        "x": {"field": "title", "type": "nominal"},
        "y": {"field": "min", "type": "quantitative"}
      }
    },
    {
      "mark": {"type": "circle", "color": "#02b6de", "size":100, "opacity": "100"},
      "encoding": {
        "x": {"field": "title", "type": "nominal"},
        "y": {"field": "min", "type": "quantitative"}
      }
    }
    
  ],
  "title": "Quiz Scores",
  "$schema": "https://vega.github.io/schema/vega-lite/v4.17.0.json",
  "datasets": {
    "data-eb6aa7311f370dcc2f64d37c32c9e387": [ 
      {
        "title": "Quiz-1",
        "my-score": 62,
        "max": 80,
        "avg": 45,
        "min": 15
      },
      {
        "title": "Quiz-2",
        "my-score": 48,
        "max": 48,
        "avg": 30,
        "min": 10
      },
      {
        "title": "Quiz-3",
        "my-score": 54,
        "max": 62,
        "avg": 36,
        "min": 12
      },
      {
        "title": "Quiz-4",
        "my-score": 27,
        "max": 69,
        "avg": 50,
        "min": 9
      },
      {
        "title": "Quiz-5",
        "my-score": 40,
        "max": 48,
        "avg": 30,
        "min": 11
      },
      {
        "title": "Quiz-6",
        "my-score": 50,
        "max": 55,
        "avg": 28,
        "min": 5
      },
    ]
  }
}

I want to render legends for the same something like this:

enter image description here

I am not able to figure out how I can do this. I checked the example given here or precisely this example. But the stock data used by this example has different schema: {symbol, date, price} and it renders different colors for different values in symbol. And vega-lite seem to auto generate legends from this schema. But, in my case, the schema is of the form {title, my-score, max, avg, min}. How do I implement legends as shown in the picture above (also note that legend for bar chart is somewhat wide)? I am fine to have somewhat different legends as long as they are sensible. But do I have to transform data to match the schema to what vega-lite stocks example schema?

PS: You can try out my visualization at this URL.

Scroll position jumping after selecting options without CTRL

I’m attempting to code my site so that users can select multiple options without the need to hold ctrl. I have a current solution that lets me select multiple options, but it seems that whenever I select an option in my window below the default dimensions of the box, the scroll jumps back up to the top.

I had found this solution but a lot of the more reliable answers seem to be in JQuery, but I’d like to stick to vanilla JS. The pure JS solution offered lower on the page gives me an error about the element part being undefined, why is that?

element.onmousedown= function(event) {
    //this == event.target
    event.preventDefault();
    var scroll_offset= this.parentElement.scrollTop;
    this.selected= !this.selected;
    this.parentElement.scrollTop= scroll_offset;
}
element.onmousemove= function(event) {
    event.preventDefault();
}

This is the code I’m currently using,

window.onmousedown = function (e) {
    var el = e.target;
    if (el.tagName.toLowerCase() == 'option' && el.parentNode.hasAttribute('multiple')) {
        e.preventDefault();

        // toggle selection
        if (el.hasAttribute('selected')) el.removeAttribute('selected');
        else el.setAttribute('selected', '');
    }
}

I’ve also seen some comments around regarding ScrollTop, but anytime I’ve tried to implement it I’ve gotten errors saying it’s not defined.

Here are a couple jsfiddles that emulate what I’m aiming for, but in JQuery:

Example 1

Example 2

My knowledge of javascript is pretty amateur so I may be missing obvious things here. Any help would be appreciated.

Issue replacing fullstop – breaks images too

We are looking to change all the fullstop colours on the site to be green. We are trying to wrap all fullstops in a span, this works however it breaks images and removes breaks from the HTML. The code is:-

<div class="container">
    <div class="row">
        <div class="col txt-col aos-init aos-animate" data-aos="fade-right">
            <h2 class="">Test<br> Test. <br> Test</h2>
            <h4>Test content.</h4>
            <p>Testing 1 2 3.</p>
        </div>
        <div class="col image-col aos-init aos-animate" data-aos="fade-left" data-aos-delay="250">
            <p><img src="fake/path.png"/></p>
        </div>
    </div>          
</div>

<script>
$('p, h1, h2, h3, h4, h5, h6').each(function () {
     $(this).html($(this).text().replace(/./g, '<span class="fs-color">.</span> '));
}); 
</script>

Could you please advise?

Thanks

Accessing HTML from JS file not working with getElementById

I am currently trying to make it so that my JavaScript file will run an <input> button that is hidden when a user places a marker on a leaflet map (or begins the process of placing it). I followed the example found here to help with this. Unfortunately, it seems that the code I added is not doing anything when I run it.

What I want to have happen: User clicks to place marker and file explorer opens up for them to select an image file.

What actually happens: The user clicks the map to place a marker and this code seems to be ignored as file explorer does not open up.

I am fairly new to HTML and JavaScript so I apologize if this is and easy to resolve issue. My code can be found below:

JS Code

var map = L.map('map').setView([0, 0], 3);
var markersArray = new Array();
var marker
var counter = 0;
var markerLayer = L.layerGroup([]);
var buttons = [];

L.tileLayer('https://api.maptiler.com/maps/streets-v2/{z}/{x}/{y}.png?key=TUHtC4pfxR178kXfCmqg', {
    attribution: '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> <a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>'
}).addTo(map)

L.Control.geocoder().addTo(map);
var markerOptions = {
    draggable: false
}
function createMarkerOnClick(evt){
    document.getElementById('imgUpload').click;
    img = document.getElementById('imgUpload').value;
    let description = prompt("Please add your description for this marker below");
    if (description == null){
        description = "No desceiption added.";
    }
    marker = new L.Marker([evt.latlng.lat, evt.latlng.lng], markerOptions).addTo(map);
    marker.bindPopup(description);
    markersArray[counter] = marker;
    marker.addTo(markerLayer);
    markerLayer.addTo(map);
    counter++;
    toggleMarker.state('disable-markers');
}

//Delete options
function delAllMarkers(){
    for(i=0; i<markersArray.length; i++){
        map.removeLayer(markersArray[i]);
    }
}
function delLastMarker(){
    map.removeLayer(markersArray[counter-1])
}


//Buttons
var toggleMarker = L.easyButton({
    states: [{
        stateName:'enable-markers',
        icon: '<center><img src="I:\maps\leafmap\location-pin.png" style="width:26px"></center>',
        title: 'Enable markers on click',
        onClick: function(control){
            control.state('disable-markers');
            map.on('click', createMarkerOnClick);
        }
    }, {
        icon: '<center><img src="I:\maps\leafmap\location-pin.png" style="width:26px"></center>',
        stateName: 'disable-markers',
        title: 'Disable markers on click',
        onClick: function(control){
            control.state('enable-markers');
            map.off('click', createMarkerOnClick)
        }
    }]
})
buttons.push(toggleMarker);

var removeAllMarkers = L.easyButton('del-all-markers', function(btn, map){
    delAllMarkers();
})
buttons.push(removeAllMarkers);

var removeLastMarker = L.easyButton('del-last-marker', function(btn, map){
    delLastMarker();
})
buttons.push(removeLastMarker);

var toolbar = L.easyBar(buttons,{
    id: 'toolbar'
}).addTo(map);

HTML File

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="leafstyle.css"/>
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI=" crossorigin="" />
    <link rel="stylesheet" href="Leaflet.EasyButton-mastersrceasy-button.css"/>
    <link rel="stylesheet" href="leaflet-control-geocoder-2.4.0distControl.Geocoder.css"/>
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM=" crossorigin=""></script>
    <script src="Leaflet.EasyButton-mastersrceasy-button.js"></script>
    <script src="leaflet-control-geocoder-2.4.0distControl.Geocoder.js"></script>

</head>
<body>
    <div id="map">
        <input type="file" accept="image/*" name="imgUpload" id="imgUpload" onchange="loadFile(event)" hidden/>
        <script type="text/javascript" src="leafymap.js"></script>
    </div>
</body>
</html>