JS – After Do-While loop, the rest of the function doesnt execute

loadNewPages = async () => {   //TODO this needs to be looping   
    this.setState({ pageCount: 3 })
    let response;
    
    do { response = await getMembers(this.state.pageCount++, this.state.size*3, this.state.divisionFilter, true),console.log(response)}
    while (response.status != 204)
    console.log("finished")
    console.log(this.props.members)
    this.handleRefresh()
        
    
  }

This code is lazy loading data from a database.
The do while loop is getting an amount of data and checking if more pages are available before re-executing.
Once the response status indicates no more pages the code below should execute, However it does not.

is this a react-js thing or am i just stupid.

Thanks in advance

my socket on connect and disconnect functions arent working (js and html/css)

this is my code; why doesn’t it send the message on connect/disconnect? when the user leaves or enters the chatroom, it is supposed to send user joined the chatroom or user left the chatroom

back end

io.on('connection', socket => {
    console.log(socket.id, "connected");
    socket.on("chat", (chat) => {
        io.sockets.emit("chat", chat);
    //msg.push([{ name: "x", key: "val" }]);
    //await db.set('messages', msg);
  });
    socket.on("connect", () => {
    
      var u = socket.username;
      socket.emit('joinedUser', u);
      const users = db.get('onlineUsers');
      users.push(socket.username);
      db.set('onlineUsers', users);
});
    socket.on("disconnect", () => {
    
      var u = socket.username;
        
  
      socket.emit('leftUser', u);
      const users = db.get('onlineUsers');
      const index = users.toString().indexOf(socket.username);
      if (index > -1) {
        users.splice(index, 1); // 2nd parameter means remove one item only
      }
});
});

front end

socket.on('joinedUser', (user) => {
var div = document.getElementById('messages-container')
div.innerHTML += `<div id = "serverMessage"><div id ="messageAuthorS">Server</div> <div id="messageValueS">${user.username} joined the chatroom</div></div>
`;
  div.scrollTop = div.scrollHeight;
});



socket.on("leftUser", (user) => {
  var div = document.getElementById('messages-container')
    div.innerHTML += `<div id = "serverMessage"><div id ="messageAuthorS">Server</div> <div id="messageValueS">${user.username} left the chatroom</div></div>
`;
div.scrollTop = div.scrollHeight;
});

Transform map(gtav) cords into pixel

So I’m thinking about a project. To get the GTA 5 Map Cords, and convert them into pixel to place some “boxs” over the map with the right cords?
I know that GTA V uses vector3, how would I do it?
My idea is to make a canvas.
I know that the map starts with var bottomLeft coords[-4000, -4000];
and topRight = [8000, 6000];

Does anyone how I could approach it?

How to perform a POST request using background task for React Native apps using expo

I am trying to log my GPS coordinates in a React-Native expo application.

The background task runs successfully and consoles log the coordinates.

Now I want to send them to my server.

For example a post request to /api/mylocation?lon=123&lat=345

I tried a regular fetch method but I get a timeout error.

regular meaning fetch(url,{ method:’POST’ etc}) (I know how to perform a basic fetch)

How can I solve this? I suspect it has to do with async and all that.

  const LOCATION_TRACKING = 'location-tracking';

  const startLocationTracking = async () => {
    console.log('startLocationTracking');
    await Location.startLocationUpdatesAsync(LOCATION_TRACKING, {
      accuracy: Location.Accuracy.Highest,
      timeInterval: 10000,
      distanceInterval: 0,
    });
    const hasStarted = await Location.hasStartedLocationUpdatesAsync(
      LOCATION_TRACKING
    );
    console.log('tracking started?', hasStarted);
  };
  


  TaskManager.defineTask(LOCATION_TRACKING, async ({ data, error }) => {
    console.log('running task:', data, error);
    // send_driver_location()

    if (error) {
      console.log('LOCATION_TRACKING task ERROR:', error);
      return;
    }
    if (data) {
      const { locations } = data;
      let lat = locations[0].coords.latitude;
      let long = locations[0].coords.longitude;
  
      console.log(
        `${new Date(Date.now()).toLocaleString()}: ${lat},${long}`

      );



      // add a fetch method here? 

      // fetch(url, {...}


    }
  });

Obviously, this will be helpful when I want to fetch tokens from my server for authentication purposes also.

Is it possible to concatenate / add a small library before initial page send?

I have some utility functions that I want available app wide, and they way I have been doing this is to add the javascript inline to my index.html file.

However, I would like to pull it out into its separate javascript file.

If I add a script tag this will add a network request which I do not want to do.

I want the javascript in its own file but sent in the initial page request for index.html.

Is there a tool that will concatenate the file in for me. Or is there some other method?

I want to replace

<script> ... my code </script>

with “something else” …

Javascript: CTRL + V sends the image from the clipboard (from the server)

I have a task which is descripted as follows:

“Purpose and need: The image attachment is added directly from the clipboard with ctrl + v.

The server has an interface at xxxxx.com. Attachments are sent on PUT request and the query portion of the address is, for example, like ?attachment_id[/request_id/urlkey], where attachment_id is something unique and invented, request_id is the request ID number, and urlkey is the “password” associated the request. The last two are therefore either defined or not at all. The content of the transmission itself must be a multipart/form-data model.

The server then returns a JSON response and if it was a success then the okMessage field can be found in it immediately at the root. Otherwise, an error message such as errorMessages (str arr) or errors (obj → srt) will return.

There are two places on this page to send an attachment:

  1. Make a New Job Request. See if this is visible. Here’s how to check it: document.getElementById('v1r').checked. If the file was successfully uploaded to the server, it will add a tag as an extension to this table: document.getElementById ('rootNew')._fields.appendixTags.i.a_newTags.

  2. Previously sent request. See if this is visible. Here’s how: document.getElementById('v2r').checked && document.getElementById ('justRequest') parentElement.style.display != 'nothing'
    (v1r and v2r are mutually exclusive, meaning only one can be visible at a time) Then, when the file has been successfully uploaded, even if you call this function, it will already be the text you want to see: l_help_addFileList(lt, name, size, mime, days) however, only name information is currently used. But where lt comes from in 1, is document.getElementById('justNew')._fields.appendixTags.i.e_sentFiles, and the conditions in section 2 are: document.getElementById('requestAttachment').e_sentFiles.

Job Request Response (Email) Not yet

In step 2, the credentials can be angled from the tag_id and tag_key data stored in the document.getElementById ('comment') element.”

I have no idea where to start. I have two javascript files: index and sendAttachment. First of all, must I modify both files or only sendAttachment one?

Secondly, what I’m missing from the code so that in addition to dragging and droping , attachments can also be attached with ctrl + v?

I appreciate your help. Thank you!

Here’s the current codes from client side (please tell me if there’s too much code for this question of mine):

index.js

//SOME CODE FIRST

        //Send button
    {
        let send = document.createElement('div');
        send.id = 'send';
        send.className = 'tr';

        let button = document.createElement('input');
        button.type = 'button';
        button.onclick = new_sendForm;
        button.value = 'Submit';
        send.appendChild(button);

        root.appendChild(send);
        root._send = button;
    }

    //Shows that notification is received
    {
        let note = document.createElement('div');
        note.id = 'new_note';
        note.style.display = 'none';
        let div = document.createElement('div');

        let text = document.createElement('h2');
        text.textContent = 'Sended successfully';
        div.appendChild(text);

        let button = document.createElement('input');
        button.type = 'button';
        button.onclick = function reset(){
            note.style.display = 'none';
            new_resetForm();
            if (root._fields.attachmentTags)
                l_addBufferedAttachmentInformation(root._fields.attachmentTags.i, []);
        };
        button.value = 'Empty form';
        div.appendChild(button);

        div.appendChild(document.createElement('br'));
        div.appendChild(document.createElement('br'));

        let p = document.createElement('i');
        p.textContent = 'You can find this and previous requests from the tab named Previous'
            + ' if you gave your email address.'
        ;
        div.appendChild(p);

        p = document.createElement('p');
        p.style.fontFamily = "'Lucida Console', monospace";
        p.innerHTML = 'Here's the link<br>';
        let a = document.createElement('a');
        a.href = '#';
        a.textContent = 'The link isn't created yet';
        p.appendChild(a);
        div.appendChild(p);

        note.appendChild(div);
        root.appendChild(note);
        root._note = note;
        root._note_a = a;
    }

    {
        let email = root._fields['email'];
        let o = s_get();
        if (email && email.i && !email.i.value && o.email)
            email.i.value = o.email;
    }
}

// ----------------------------------------------------------------------------


function show_comment(){
    let comment = document.getElementById('comment');
    let selection = null;{
        let inputs = comment.getElementsByTagName('input');
        for (let i=0, ii=inputs.length; i<ii; i++){
            let input = inputs.item(i);
            if (input.checked){
                selection = input.value;
                break;
            }
        }
    }
    let n_comment = document.getElementById('n_comment');
    let n_comment_error = document.getElementById('n_comment_error');
    let n_comment_button = document.getElementById('n_comment_button');
    if (!selection)
        n_comment_error.textContent = 'Not done';
    else if (!n_comment.value.trim())
        n_comment_error.textContent = 'Comment missing';
    else {
        n_comment_error.textContent = '';
        n_comment_button.disabled = true;
        let post = {
            feature: "addComment",
            getRequest: {
                id: comment.key_id,
                urlkey: comment.key_key,
                status: selection,
                description: n_comment.value
            }
        }
        xhr(
            function ok(json){
                n_comment_button.disabled = false;
                if (json.errorMessages)
                    n_comment_error.innerHTML = json.errorMessages.join('<br>');
                else
                    n_comment.value = '';
                if (json.requests && json.requests[0]){
                    let request = json.requests[0];
                    let label = document.getElementById('rootRequest').getElementsByTagName('h3').item(0);
                    if (label && request.jira_fields && request.jira_fields.description){
                        label.nextElementSibling.innerHTML = '';
                        doc2html(request.jira_fields.description, bella.nextElementSibling);
                    }
                }
            },
            '/api',
            JSON.stringify(post),
            function err(json){
                n_comment_button.disabled = false;
                n_comment_error.textContent = 'Sending failed';
            }
        );
    }
}

//OTHER CODES BEFORE NEXT ONES:

        //Attachments part

        let requestAttachment = document.getElementById('requestAttachment');
        if (request.jira_fields && request.jira_fields.attachment)
            l_addJiraAttachmentInfo(requestAttachment, request.jira_fields.attachment);
        else if (pyynto.attachmentTags)
            l_addBufferedAttachmentInfo(requestAttachment, request.attachmentTags);
        else
            l_addBufferedAttachmentInfo(requestAttachment, []);
    } else {
        root.innerHTML = 'Didn't find the request';
    }
    root.parentElement.style.display = 'inline-block';
}

function show_get(id, urlkey){
    xhr(
        function ok(json){
            show_show(json);
        },
        '/api',
        JSON.stringify({
            feature: 'get',
            getRequest: {
                id: id,
                urlkey: urlkey
            }
        }),
        function err(json){
            let root = document.getElementById('rootRequest');
            root.innerHTML = '<b>Download failed</b>';
        }
    );
}

function show_initLomake(){
    let get = getParameters();
    let root = document.getElementById('rootRequest');
    if (get['id'] && get['idKey']){
        root.innerHTML = '<i>Searching...</i>';
        show_get(get['id'], get['idKey']);
        //Switching page
        document.getElementById('v2r').checked = true;
    } else {
        root.parentElement.style.display = 'none';
    }
    let requestAttachment = document.getElementById('requestAttachment');
    let comment = document.getElementById('comment');
    if (typeof l_createForm === 'function' && requestAttachment && comment)
        l_createForm(requestAttachment, comment);
    else if (comment)
        requestAttachment.parentElement.style.display = 'none';
}

    function list_sendLink(email){
    if (email){
        xhr(
            function ok(json){
                let root = document.getElementById('rootList');
                if (json.okMessage)
                    root.textContent = json.okMessage;
                else if (json.errors && json.errors['sendMssage']){
                    let div = document.createElement('div');
                    div.textContent = json.errors['sendMessage'];
                    div.className = 'error';
                    root.appendChild(div);
                } else if (json.errorMessages && json.errorMessages[0]){
                    let div = document.createElement('div');
                    div.textContent = json.errorMessages[0];
                    div.className = 'error';
                    root.appendChild(div);
                } else
                    root.innerHTML = "Something went wrong. Don't know what or where.";
            },
            '/api',
            JSON.stringify({
                feature: 'sendListTag',
                newForm: {
                    email: email
                }
            }),
            function err(json){
                let root = document.getElementById('rootList');
                let div = document.createElement('div');
                div.textContent = 'Sending the request to server failed???';
                div.className = 'error';
                root.appendChild(div);
            }
        );
    }
}

function list_initShowPrevious(){
    let get = getParameters();
    let sailo = s_get();
    let root = document.getElementById('rootList');
    let mm_list = document.getElementById('mm_list');

    let email = get['email'];
    let listTag = get['list'];

    if (sailo.email && sailo.listTag){
        s_forgetButton(true);
        if (!email || !listag || sailo.email == email && sailo.listTag == listTag){
            email = sailo.email;
            listTag = sailo.listTag;
            mm_list.innerHTML = 'Email and list tags.';
        } else {
            mm_list.innerHTML = 'Email and list tag, but they differ!<br><i>If you want to update, you must forget old infos first.</i>';
        }
    } else if (email && listTag){
        s_post(email, listTag);
        mm_list.innerHTML = 'Email and list tags (saved now).';
        s_forgetButton(true);
    } else {
        mm_list.innerHTML = 'Nothing';
    }

    if (email && listTag){
        root.innerHTML = '<i>Searching...</i>';
        list_get(email, listTag);

        if (!get['form'])
            document.getElementById('v2r').checked = true;
    }
}

// ----------------------------------------------------------------------------

function init(){
    //New form?
    xhr(
        function settingsGot(json){
            new_initForm(json);
            window._settings = json;
            list_initShowPrevious();
            show_initForm();
        },
        'form.new.json',
        null,
        null
    );
}

sentAttachment.js

'use strict';

function l_createForm(root, settingSource){
    if (!root || !ss || !ss.SimpleUpload){
        console.error("Formatting of downloading attachment file failed.");
    } else {
        root.a_settingSource = settingSource;
        root.a_newTags = [];
        {
            let sendedFiles = document.createElement('fieldset');
            root.e_SendedFiles = sendedFiles;
            sendedFiles.className = 'sendedFiles';
            let legend = document.createElement('legend');
            legend.innerHTML = 'Sended files';
            sendedFiles.appendChild(legend);
            root.appendChild(sendedFiles);
        }

        {
            let progressBox = document.createElement('div');
            root.e_progressBox = progressBox;
            progressBox.className = 'progressBox';
            root.appendChild(progressBox);
        }

        {
            let key = document.createElement('p');
            root.e_key = key;
            key.className = 'key';
            key.innerHTML = '<span>Drag and drop the files you want to send to the square above</span> ' +
                'or <a>click here</a>';
            root.e_clicking = key.lastElementChild;
            root.appendChild(key);
        }

        root.e_fileUpload = new ss.SimpleUpload({
            button: [root.e_sendedFiles, root.e_clicking],
            url: function before(xhr, settings){
                let extra = '';
                if (settingSource && settingSource.tag_id && settingSource.tag_key)
                    extra = '/' + settingSource.tag_id + '/' + settingSource.tag_key;
                return location.protocol +
                    '//' + location.host +
                    '/api?' + 
                    (Date.now()) +
                    extra
                ;
            },
            name: "file",
            method: "PUT",
            dropzone: root,
            dragClass: 'fileOn',
            encodeHeaders: true,
            cors: false,
            multiple: true,
            multipleSelect: true,
            noParams: true,
            multipart: true,
            autoSubmit: true,
            responseType: "json",
            debug: false,
            onDone: function sendingPassed(
                fileName,//String
                statusCode,//the response status code, if any
                statusText,//the response status code, if any
                json,//false
                button,//Button which started sending
                fileSize//number or null
            ){
                let sendedFiles = root.e_sendedFiles;
                if (sendedFiles){
                    l_help_addFileToList(
                        sendedFiles,
                        fileName,
                        fileSize,
                        null,
                        null
                    );
                    if (json && json.attachmentTag)
                        root.a_newTags.push(json.attachmentTag);
                } else {
                    alert('File "' + fileName + '" sended successfully.');
                }
            },
            onError: function sendingError(
                fileName,//String
                errorType,//"error" or "parseerror"
                statusCode,//the response status code, if any
                statusText,//the response status code, if any
                answer,//false
                button,//Button which started sending
                fileSize//number or null
            ){
                alert('"' + fileName + '": ' + statusText);
            },
            onSubmit: function(filename, extension) {
                // Create the elements of our progress bar
                var progress = document.createElement('div'), // container for progress bar
                bar = document.createElement('div'), // actual progress bar
                fileSize = document.createElement('div'), // container for upload file size
                wrapper = document.createElement('div'), // container for this progress bar
                //declare somewhere: <div id="progressBox"></div> where you want to show the progress-bar(s)
                progressBox = root.e_progressBox; //on page container for progress bars

                // Assign each element its corresponding class
                progress.className = 'progress progress-striped';
                bar.className = 'progress-bar progress-bar-success';
                fileSize.className = 'size';
                wrapper.className = 'wrapper';

                // Assemble the progress bar and add it to the page
                progress.appendChild(bar); 
                wrapper.innerHTML = '<div class="name">Sending <b>'+filename+'</b></div>'; // filename is passed to onSubmit()
                wrapper.appendChild(fileSize);
                wrapper.appendChild(progress);                                       
                progressBox.appendChild(wrapper); // just an element on the page to hold the progress bars    

                // Assign roles to the elements of the progress bar
                this.setProgressBar(bar); // will serve as the actual progress bar
                this.setFileSizeBox(fileSize); // display file size beside progress bar
                this.setProgressContainer(wrapper); // designate the containing div to be removed after upload
            }
        });
    }
}

function l_help_addFileToList(root, name, size, mime, date){
    let square = document.createElement('div');
    square.className = 'square';

    let text = document.createElement('span');
    text.className = 'name';
    text.innerHTML = name;
    square.appendChild(text);

/*
    let size = document.createElement('i');
    size.className = 'size';
    size.innerHTML = size;
    square.appendChild(size);
*/

    root.appendChild(square);
}

function l_addJiraAttachmentInfo(root, attachment_arr){
    if (root.e_sendedFiles && attachment_arr instanceof Array){
        root.e_sendedFiles.innerHTML = '';
        root.a_newTags = [];
        for (let i=0, ii=attachment_arr.length; i<ii; i++){
            let a = attachment_arr[i];
            l_help_addFileToList(
                root.e_sendedFiles,
                a.filename,
                a.size,
                a.mimeType,
                a.created
            );
        }
    }
}

function l_addBufferedAttachmentInfo(root, attachmentTags){
    if (root.e_sendedFiles && attachmentTags instanceof Array){
        root.e_sendedFiles.innerHTML = '';
        root.a_newTags = [];
        for (let i=0, ii=attachmentTags.length; i<ii; i++){
            let a = attachmentTags[i];
            l_help_addFileToList(
                root.e_sendedFiles,
                'Sending_' + a,
                -1,
                null,
                null
            );
        }
    }
}

function l_getSendedTags(root){
    if (root.a_newTags)
        return root.a_newTags;
    else
        return null;
}

How do you access the object in a JS promise and output it into your HTML in React Native?

I’m trying to get the object from in my code in result.data.name. It should just be a string but isn’t outputting properly. I assume I am grabbing the unfulfilled promise and not the fulfilled promise but am not sure.

I’ve tried to output it by changing the

        
<Text>{project.toString()}</Text>

and it outputs [object Object] which is not exactly what I want.

Error:

Error: Objects are not valid as a React child (found: object with keys {_U, _V, _W, _X}). If you meant to render a collection of children, use an array instead.

Code:

import React from "react";
import styled from "styled-components";

const Patch = require("@patch-technology/patch").default;
const patch = Patch("API_KEY");

const runningTide = "PROJECT_KEY";
export const project = patch.projects
  .retrieveProject(runningTide)
  .then(function (result) {
    return result.data.name;
  })
  .catch((error) => console.log(error));

class PatchModule extends React.Component {
  navigationOptions = { header: { visible: false } };

  render() {
    return (
      <Container>
        <Text>{project}</Text>
        <Text>Testing</Text>
      </Container>
    );
  }
}

export default PatchModule;

const Container = styled.View`
  flex: 1;
  background-color: #ffffff;
  border-radius: 10px;
  justify-content: center;
`;

const Text = styled.Text`
  font-size: 10px;
  color: #19456b;
  font-weight: 600;
  top: 0;
  left: 0;
  margin-top: 30px;
  margin-right: 20px;
  margin-left: 20px;
`;

Why is VSCode not indenting .js file properly?

I am doing tutorial about full stack web development with javascript and react on the front. I have very very litle knowledge of html and no knowledge on javascript and react beforehand.

I have recurring problem where I write code to .js file, but indentation seems to be messed up and causes things to not work properly. Otherwise code is perfect.

Here is example of what I wrote (that didin’t work).

import React, { Component } from 'react';

export default class RoomJoinPage extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return <p>This is the Join Room page</p>
    }
}

Here is example of working code:

import React, { Component } from "react";

export default class RoomJoinPage extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return <p>This is the room join page</p>;
  }
}

I get that indentation has to be done properly, but why vscode does not indent these correct automatically? Am I to learn writing code in .js files so that I first backspace improper indent and then double tap space to make it right? What am I missing here?

How to retrive customer info or payment intent in succes page stripe php slim

hi i want to take amount, customer name and email on my success page but I am struggling to do.

this is my PHP server side codes which send request to stripe.

<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

use SlimHttpRequest;
use SlimHttpResponse;
use StripeStripe;




require 'vendor/autoload.php';

$dotenv = DotenvDotenv::create(__DIR__);
$dotenv->load();

require './config.php';

$app = new SlimApp;

$app->add(function ($request, $response, $next) {
    Stripe::setApiKey(getenv('STRIPE_SECRET_KEY'));
    return $next($request, $response);
});

$app->get('/', function (Request $request, Response $response, array $args) {
  return $response->write(file_get_contents(getenv('STATIC_DIR') . './grid-test.html','/index-copy.html'));
});

$app->post('/checkout_sessions', function(Request $request, Response $response) use ($app)  {
  $params = json_decode($request->getBody());
  $payment_method_types = [
    'usd' => ['card'],
    'eur' => ['card'],
    'cad' => ['card']
  ];
  $products = [
    'Private' => 'prod_435646574',
  ];

  $session = StripeCheckoutSession::create([
    'success_url' => 'http://localhost:4242/success.html?session_id={CHECKOUT_SESSION_ID}',
    'cancel_url' => 'http://localhost:4242/?cancel=true',
    'mode' => 'payment',
    'payment_method_types' => ['card'],
    'payment_intent_data' => [
      'metadata' => [
        'package' => $params->package,
        'date' => $params->datepicker,
        'no of adults' => $params->adults,
        'no of children' => $params->children,
        'occupancy' => $params->occupancy,
        'tour' => $params->tour,
        'location' => $params->location,
      ]
    ],
    'metadata' => [
      'package' => $params->package,
      'date' => $params->datepicker,
      'no of adults' => $params->adults,
      'no of children' => $params->children,
      'occupancy' => $params->occupancy,
      'tour' => $params->tour,
      'location' => $params->location,
    ],
    'submit_type' => 'donate',
    'line_items' => [[
      'price_data' => [
        'currency' => 'aed',
        'product' => $products[$params->package],
        'unit_amount' => $params->amount,
      ],
      'quantity' => 1,
    ]],
    'phone_number_collection' => [
      'enabled' => true,
    ],
    
  ]);

  return $response->withJson([
    'id' => $session->id
  ]);
});




$app->run();

this is my success page which I am not able to get checkout session or payment intent details

var params = new URLSearchParams(window.location.search);
var sessionId = params.get('id');
var amount = document.getElementById('amount')

fetch('/get-session?id=' + sessionId)
.then((Response) => Response.json())
.then((session) => {
    amount.innerText = session.payment_intent.amount;
    
})
.catch((error) => {
    console.error('Error:', error);
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Thank You For Order</title>
    

</head>
<body>
  <div id="main">
    <div id="checkout">
      <div id="payment-form">
        <h1>Success!</h1>

        <p>
        Thanks so much for donating <strong id="amount"></strong> to 

        </p>

        <a href="/">Donate More?!</a>
      </div>
    </div>
  </div>
</body>

hi i want to take amount, customer name and email on my success page but I am struggling to do.

Firebase return [Object object] [duplicate]

I’m trying to get the value of a child that has been added to my database with cloud functions and then send this value with a push notification to my mobile app. The problem is that firebase instead of giving me the value of the child it gives me a [ObjectObject] and I can’t find the problem inside my code.

My index.js:

//import firebase functions modules
const functions = require('firebase-functions');
//import admin module
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.pushNotification = functions.database.ref('/users').onCreate((snapshot, context) => {

    //  Get the current value of what was written to the Realtime Database.
    const valueObject = snapshot.after.val();
    functions.logger.log("value is: " + valueObject);

    // Create a notification
    const payload = {
        notification: {
            title: "Value is: " + valueObject,
            body: "This is a test",
            sound: "default"
        }
    };

    //Create an options object that contains the time to live for the notification and the priority
    const options = {
        priority: "high",
        timeToLive: 60 * 60 * 24
    };

    return admin.messaging().sendToTopic("pushNotifications", payload, options);
});

mocking document.domain and other objects in jest

I am trying to run tests in jest at the moment, at the moment I am getting an error that looks like this,

TypeError: Cannot read property 'indexOf' of undefined

      194 |     if (this.config.storage_host) {
      195 |       domain = this.config.storage_host;
    > 196 |     } else if (document.domain.indexOf("example") > 0) {
          |                                ^
      197 |       let domainParts: string[] = document.domain.split(".");
      198 |       domainParts.splice(0, 1);
      199 |       domain = domainParts.join(".");

The problem it would seem is that document.domain is undefined, how would I go about creating a document.domain for the tests? I assume I would mock it somehow, I have tried,

    Object.defineProperty(document, 'domain' {
        writable: true,
        value: 'https://www.example.com'
    });

but that did not make any change. I will also need to mock an object that is used throughout the application how would I go about that? The object is called ProvideState and has attributes like,

const ProvideState = {
    state: {
        app: 'client'
        context: '',
   }
}

Button refreshes page, and UseEffect not working

I have two buttons in my react.js project, when i click on the css should switch. To do this i have a onClick call to a function flip which changes the value of a state pathoButton from true to false (or vice versa). Then i have a useEffect that should only be run when pathoButton is changed and this alters the html. For some reason every time i click a button the whole page refreshes and im not sure what courses this. here is a snippet of some of the code.

where pathoButton is originally set

    const [userSettings, setuserSettings] = useState(
        {
            pathoButton: true,
        } 
    );

The two buttons which are pathologyButton and treatmentButton when the treatmentButton is clicked flip is called

return (
      <div className="input-group top-gap">
          <form className="form-length">
              <div className="input-group">
                <button className="pathologyButton">  <dt>Pathology</dt> </button>
                <button className="treatmentButton" onClick={()=>flip()}>  <dt>Treatment</dt> </button> 
              </div>
            <div className="svg-form">
                {displayAnimal()}
                  
            </div>
              
          </form>
          <form className='form-length'>
              <input type="Animal" class="animal-input" placeholder="Search by owner name or animal..." /> 
          </form>

      </div>
    );

flip and my use effect, i have tried window.location.reload(false); but it does not work

    function flip(e){
        window.location.reload(false);
        const pathoB = ! userSettings.pathoButton        
        setuserSettings((prevState) => {
            return { ...prevState, pathoButton: pathoB };
          });
    }

    useEffect(() => {
        console.log(userSettings.pathoButton, '<---lognnn')
        if (userSettings.pathoButton) {
            return (<div> 
                <button className="pathologyButton" onClick={()=>flip()}>  <dt>Pathology</dt> </button>
                <button className="treatmentButton" onClick={()=>flip()}>  <dt>Treatment</dt> </button> 
            </div>)
        } else {
            return (<div>
                <button className="treatmentButton" onClick={()=>flip()}>  <dt>Pathology</dt> </button>
                <button className="pathologyButton" onClick={()=>flip()}>  <dt>Treatment</dt> </button> 
            </div>
            )
        }
    }, [userSettings.pathoButton])


Sorry if this is a repost of a question! i dont think it is but could be as im unsure what causes the page to refresh and any help or advice would be awesome!

NuxtJS /Vue not firing scroll event

I’m using Vue3 and NuxtJS,but it seems like scroll event wont fire. Nothing happens after I scroll,nor I don’t have any errors

methods: {
    handleScroll () {
      console.log('scrolled')
      }
  },
created(){
   if(process.client){
    window.addEventListener('scroll', this.handleScroll);
    console.log(window)

}
  },
  destroyed () {
    if(process.client){
    window.removeEventListener('scroll', this.handleScroll);
    }
}