Error: Adding data in a map in Firestore but the the new data saves as an array inside the map instead of a field

I have this colorMap from firestore which is a map.

enter image description here

What I’m trying to do is add more data in the colorMap. Let’s say I have these:

Green: 50

Black 50

Red 20

And I wanted to add Pink : 80. But what my code currently does is, if I’ll add Pink: 80, the Pink becomes an array instead of a field. This is what happens when I save it in Firestore.

enter image description here

Expected output
Once I’ll add Black : 80, it should be the same data types with the other colors as well.

Submitting in firestore:

  //converting colorList to colorMap (map)
  const colorMap = colorList.reduce(function (map, obj) {
    map[obj.color] = obj.colorStocks;
    return map;
  }, {});

  const colorSave = Object.keys(colorMap);
  const qty = Object.values(colorMap);

  const handleSubmit = (index) => async (e) => {
    e.preventDefault();

    const ref = doc(db, "products", state);
    await updateDoc(ref, {
      ...product[index],
      [`colorMap.${colorSave}`]: qty,
    });
    console.log("done");
  };

This is the console for the colorMap:

enter image description here

Form

 {colorList.map((singleColor, index) => (
                    <div key={index}>
                        <>
                            <>
                                <TextField
                                  label="Color"
                                  name="color"
                                  type="text"
                                  id="color"
                                  required
                                  value={singleColor.color}
                                  onChange={(e) => handleColorChange(e, index)}
                                />
                                <TextField
                                  label="Stocks"
                                  name="colorStocks"
                                  type="number"
                                  id="colorStocks"
                                  required
                                  value={singleColor.colorStocks}
                                  onChange={(e) => handleColorChange(e, index)}
                                />
                            </>
                        </>
                      </div>
                      <br />
                        //button to remove the row of the textfield
                    </div>
                  ))}
                    //button to add the row of the textfield

How to separate words by commas?

I would like to split words with comma, so I can later highlight it with mouse hover.
But I can’t get it to work, I don’t want to split words with - also.

HTML

<p class="texthover"> Name, Name-01, Name-02, Name, Name</p>

CSS

.texthover span {
    color: #F2668F;
    transition: color .3s;
}

.texthover span:hover {
    color: #023C4F;
    transition: color .3s;
}

First code I have, words are all split:

$(function() {
    $('.texthover').each(function() {
        var $this = $(this);
        $this.html($this.text().replace(/b(w+)b/g, "<span>$1</span>"));
    });
});

I tried it this way too, while I can get the words, I lose the commas in text:

var text = document.querySelector('.texthover').innerHTML;
var old_html = text.split(",");
var new_html = "";
for (var i = 0; i < old_html.length; i++) {
    new_html = new_html + " <span class='text-"+i+"'>" + old_html[i]  + " </span>";
    document.querySelector('.texthover').innerHTML = new_html;
}

React Native: How do I pass auth token from Sign in to be used in future API calls?

When user logs in with correct credentials it returns a token. How can I pass that token for it to be used in future API calls?

Here is my SignIn code:

const SignIn = () => {
    const navigation = useNavigation();

    const {
        control, 
        handleSubmit, 
        formState: {errors},
    } = useForm();

    const onSignIn = (data) => {
        fetch('http://sign-in/',
            {
                method: 'POST',
                headers: {
                    "Content-Type": "application/json",
                    "Accept": 'application/json',
                },
                body: JSON.stringify(data),
            },
            console.log(data)
        )
        .then( data => data.json())
        .then( data => {
            navigation.navigate(BottomTab);
        })
        .catch(error => console.error(error));
    };

    return (
        <View style={styles.root}>
            <Text style={styles.text}>sign in</Text>
            <CustomInput
                name={"username"} 
                placeholder= 'username:'
            />
            <CustomInput
                name={"password"}
                placeholder= 'password:'
            />
            <CustomButton onPress={handleSubmit(onSignIn)} />
        </View>
    );
};

After user signs in it navigates to the bottom tab navigator:

const Tab = createBottomTabNavigator();

const BottomTab = () => {

    return (
        <Tab.Navigator
            initialRouteName={"Home"}>
            <Tab.Screen name='Home' component={Home} />
            <Tab.Screen name='Profile' component={Profile} />
        </Tab.Navigator>
    );
};

Which is nested in a Navigator:

const Stack = createNativeStackNavigator();

const Navigation = () => {

    return (
        <NavigationContainer >
            <Stack.Navigator screenOptions={{headerShown:false}} >
                <Stack.Screen name="SignIn" component={SignIn} />
                <Stack.Screen name="BottomTab" component={BottomTab} />
            </Stack.Navigator>
        </NavigationContainer>
    );
};

Which is called in my App.js:

function App() {

  return (
    <SafeAreaView style={styles.root}>
      <StatusBar barStyle="light-content" />
        <Navigation />
      </SafeAreaView>
    ); 
  }
  
  const styles = StyleSheet.create({
    root: {
      backgroundColor: '#121212',
      flex: 1
    }
  });
  
export default App;

I’m not sure where and how to pass the token for it to give me access to it in future API calls.

Do I do that in the Bottom Tab or when i make the API calls in the future?

Appreciate any help!

How can I turn the container elements in this incremental game into buttons? [closed]

I’m trying to help a developer make their incremental game more accessible to blind users who use a screen reader like I do. The game has lots of elements that are clickable but not buttons or links or anything, so I’m trying to change them so they’re easier to navigate to with a screen reader, but the way the game has them set up makes it difficult to turn them into individual buttons. I tried and wound up turning a whole section into one big button. I know HTML and am learning JavaScript, but I think this issue is a little beyond my knowledge. It’s difficult to share blocks of code because of the setup, so here’s a link to the code.
In case it helps, you can play the game here.
Can anyone help me figure out how to change the clickable items into buttons?

Send recorded video using getUserMedia through form without using FormData

I have a form where users can record themselves with their webcam using getUserMedia, and I need to send the file they record to another page before saving the file to the server.

My question is what would be the best way to do that? So far I’ve generated a blob of the video, how do I send this through my form to the next page so I can access the file and then store it on the server?

Currently I’m generating the blob like so, which works:

let videoURL = window.URL.createObjectURL(blob, {autoRevoke: false});

But I’m not sure how I can send this file as part of the form’s POST request without using AJAX and FormData. Is it even possible or am I approaching this incorrectly?

Why is my mongoose query with $gt combined with $size not working?

here is my mongoose query(and the router):

router.get('/reportsRegular', function(req,res,next){
  Question.find({reports: {$size: {$gt: 0}}, checked: false}).sort({reports: -1}).limit(20).exec(function(err,results){
    console.log(results)
    res.render('reports', {type: 'regular', user: req.user, reports: results})
  })

and it seems there is a problem with the first find condition, when I remove the $gt to 1 instead it works, but it wont work in cases with more then one, so I need to use $gt.
here is an example JSON document that should work but does not get found:

  {
    _id: new ObjectId("6212e77aa1e98ae3282a61e6"),
    title: 'TOMATOOOOOO',
    text: '<p>AAAAAAAAAAAAAAAA</p>',
    authorUsername: 'SweetWhite',
    dateCreated: 2022-02-21T01:14:34.901Z,
    answers: [],
    likes: [ 0 ],
    dislikes: [ 0 ],
    tag: 'Languages',
    views: [ 1, 'SweetWhite' ],
    reports: [ 'SweetWhite' ],
    checked: false,
    reportsNested: [],
    __v: 0
  }

it should get found since the size of the reports array is bigger then zero, and the checked value is false.
What am I doing wrong?

Thanks!

Randomly generate += or -= javascript

Hi i am trying to assign either += or -= to an object position.
Firstly I have random math choosing a number:

var min = 9;
 var max = 11;
 var pos = Math.floor(Math.random() * (max - min + 1)) + min;

I am trying to add the out come of pos to this._target.position.z and this._target.position.x but I want it to be randomly either added or subtracted

so the random out come should be for the Z position should be either:

this._target.position.z += pos;

or

this._target.position.z -= pos;

and then for the X position should be either:

this._target.position.x += pos;

or

this._target.position.x -= pos;

thanks in advance.

Weird line bug when animating a falling sprite using JavaScript canvas

I’m trying to move a block of butter down a canvas window. Here is the code sandbox: https://codesandbox.io/s/empty-sandbox-forked-tygc5z?file=/index.html

The important code is index.js:

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

window.onresize = function () {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
};

const arr = ["butter", "bread", "cheese"];
const sprites = [];
const tilesheet = new Image();

const butter1 = {
  img: tilesheet,
  sourceWidth: 24,
  sourceHeight: 60,
  sourceX: 3,
  sourceY: 2,
  vy: 0,
  timer: 0,
  x: 0,
  y: 0,
  scale: 1,
  visible: false
};
const butter2 = {
  img: tilesheet,
  sourceWidth: 33,
  sourceHeight: 60,
  sourceX: 27,
  sourceY: 2,
  vy: 0,
  timer: 0,
  x: 0,
  y: 0,
  scale: 1,
  visible: false
};
const butter3 = {
  img: tilesheet,
  sourceWidth: 24,
  sourceHeight: 60,
  sourceX: 60,
  sourceY: 2,
  vy: 0,
  timer: 0,
  x: 60,
  y: 0,
  scale: 1,
  visible: false
};
tilesheet.addEventListener(
  "load",
  () => {
    arr.forEach((_, i) => {
      const b1 = { ...butter1 };
      b1.timer = i * 62;
      sprites.push(b1);

      const b2 = { ...butter2 };
      b2.x = b1.x + b1.sourceWidth * b1.scale;
      b2.timer = b1.timer;
      sprites.push(b2);

      const b3 = { ...butter3 };
      b3.x = b2.x + b2.sourceWidth * b2.scale;
      b3.timer = b2.timer;
      sprites.push(b3);
    });
    render();
  },
  false
);
tilesheet.src = "./src/sample.png";

function render() {
  requestAnimationFrame(render);
  //console.log(arr.length, sprites.length);
  sprites.forEach((sprite, i) => {
    sprite.timer -= 0.3;

    if (sprite.timer <= 0) {
      sprite.visible = true;
    }

    if (sprite.visible) {
      sprite.vy = 0.3;
      sprite.y += sprite.vy;
    }
  });
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "rgba(229, 242, 24, 1)";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  sprites.forEach((sprite) => {
    if (sprite.visible) {
      ctx.drawImage(
        sprite.img,
        sprite.sourceX,
        sprite.sourceY,
        sprite.sourceWidth,
        sprite.sourceHeight,
        sprite.x,
        sprite.y,
        sprite.sourceWidth * sprite.scale,
        sprite.sourceHeight * sprite.scale
      );
    }
  });
}

As you can see in the code sandbox, there is a weird line appearing when the blocks of butter go down the window:
enter image description here
It is not there when the speed is 1 instead of 0.3 or when the butter is not moving.

Is there anyway I can get rid of the weird line? Thanks

How do I send a variable from Express.js backend to React.js frontend?

I am trying to send my variable ‘backEndResponse’ with its value from my Express.js backend to my React.js Frontend. I am not quite sure how to send a variable from the backend to the frontend. I have searched around and can’t find any good resources. I would appreciate any help.

Express.js Backend

 function getcookie(req) {
        var authCookie = req.headers.cookie;
        try{
        return authCookie
            .split('; ')
            .find(row => row.startsWith('Auth='))
            .split('=')[1];
        } finally {
            if (authCookie = result) {
                backEndResponse = true
                console.log(backEndResponse);
                console.log(result);
            } else {
                backEndResponse = false
                console.log(backEndResponse);
                console.log(result);
            }
        }
    }
    
    app.get('/auth', (req, res) => {
        backEndResponse
    });

Frontend React.js

let backEndResponse = null

axios.get('http://localhost:5000/auth', { withCredentials: true }).then((res) => {
        // backEndResponse
    })

const useAuth = () => {
    if (backEndResponse) {
        const authorized = {loggedIn: true}
        return authorized && authorized.loggedIn;
    } else {
        const authorized = {loggedIn: false}
        return authorized && authorized.loggedIn;
    }
};

“this” not working inside deep watcher with Vue JS 3 and TypeScript

I am having some troubles trying to use “this” in a deep watcher. It seems like inside the deep watcher, the word this points to the context of the object watcher and it is not able to get an attribute declared in the data() function. My script tag looks like this:

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "App",
  data() {
    return {
      totalPrice: 0,
      cart: new Array<any>()
    };
  },
  watcher: {
    cart: {
      handler(cart: Array<any>) {
        this.totalPrice = cart.reduce((prev, curr) => {
          const prevPrice = prev.price || prev;
          const prevQuantity = prev.quantity || 1;
          return prevPrice * prevQuantity + curr.price * curr.quantity;
        }, 0);
      },
      deep: true
    },
  },
});
</script>

So, when I do npm run serve I get this error in console:

ERROR in src/App.vue:134:14
TS2339: Property 'totalPrice' does not exist on type '{ handler(cart: any[]): void; deep: boolean; }'.
    133 |       handler(cart: Array<any>) {
  > 134 |         this.totalPrice = cart.reduce((prev, curr) => {
        |              ^^^^^^^^^^
    135 |           const prevPrice = prev.price || prev;
    136 |           const prevQuantity = prev.quantity || 1;
    137 |           return prevPrice * prevQuantity + curr.price * curr.quantity;

I’m new with vue, so I’ll be happy receiving any suggestion. Thanks in advance.

Fastest way to clean path collisions in array of strings

This is a hard one to explain, but here goes. I need to clean an array of ‘path’ strings where if a path has sub properties it not include the top level property. but only the child properties

E.g

[
  'firstName',
  'address',
  'address.local.addressLine1',
  'address.local.addressLine2',
  'address.local',
]

Should become:

[
  'firstName',
  'address.local.addressLine1',
  'address.local.addressLine2',
  'address.local',
]

I have a fairly verbose function kind of working so far, but looking to see if there is a more elegant/better solution than this:

function cleanCollisions(array) {

        var output = [];

        // return [...new Set(array)];
        var map = array.reduce(function(set, field) {
            if (!Boolean(field)) {
                return set;
            }

            ////////////////

            var rootKey = field.split('.')[0];
            if(!set[rootKey]) {
                set[rootKey] =[];
            }

            var count = field.split('.').length -1;
            if(count) {
                set[rootKey].push(field);
            }


            return set;
        }, {})


        for(const key in map) {
            value = map[key];
            if(value.length) {
                output.push(value);
            } else {
                output.push(key);
            }
        }

        ////////////////

        return output.flat();
    }

Object destructuring default parameters get all arguments

I have a js file with an imported default options and function as below. I am trying to get all the arguments in the function, however it appears that they cannot be used.

import {defaultOptions} from "../defaults.js"

export function getConfig({
  width = defaultOptions.width,
  height = defaultOptions.height,
  fontsize = defaultOptions.fontsize
} = {}) {
   // I want to get all the arguments 
   console.log(arguments); 
}

When I call the function with no parameters like getConfig() and console.log(width) then it shows the width from the defaultOptions from the defaults.js. However the console.log(arguments) returns Arguments object with length 1 where index 0 : undefined.

Is there a way I can get all the arguments in such a function?

Split variable into several to get infos

I would like to separate this in Javascript and create variables infos1, infos2 ….

So I need a function to separate all the info.

<option value="[infos1][infos2][infos3][infos4]"></option>

var InfosInitial = $('#insert').find("option:selected").val();

var infos1 = ?;

var infos2 = ?;

Thanks you in advance !

function not passing arguments object test

I’m currently completing an assignment where I need to pass the following test

* should work on an arguments object

Here is my code.

function first (array, n) {
  var result = [];
  if (Array.isArray(array)) {
    if (n && n > 0) {
      var number = n > array.length ? array.length : n;
      for (var i=0; i < number; i++) {
        result.push(array[i]);
      }
    } else {
      result.push(array[0]);
    }
    return result;
  } else {
    return result;
  }
};

Im not sure what lines I need to ammend to make it pass this test, can anyone help me?

WHy in my recursion function the code after the if condition is repeated?

// program to count down numbers to 1
function countDown(number) {

  // display the number
  console.log(number);

  // decrease the number value
  const newNumber = number - 1;

  // base case
  if (newNumber > 0) {
    countDown(newNumber);
  }
  console.log(newNumber);
}

countDown(4); 

// output => 4 3 2 1 0 1 2 3

I can’t visualize what happens after the if condition. I mean I understand that there is “loop” with countDown(newNumber). But I don’t understand why there is the output 0 1 2 3. I know I can put an else keyword, but I’d like to understand why JS engine after finishing the recursion it prints four times console.log(newNumber).