Maintaining Socket Connection in Mobile Sleep Mode – MERN Stack

Question:

I’m working on a MERN stack application where I’m utilizing Socket.IO for real-time communication. Everything works well, but I’m facing an issue when the mobile device goes into sleep mode. The socket connection seems to be getting disrupted during this state.

Context:

I have a backend setup using Node.js and Socket.IO, and on the frontend side, I’m using React with the useEffect hook to establish a socket connection when the component mounts. Here’s a simplified version of my code:

Backend (socket.js):

// ... (previous code)
io.on("connect", (socket) => {
  socket.on("join", async () => {
    // some code...
  } catch (error) {
    // handle error...
  }
});

Frontend (product.js):

// ... (previous code)
useEffect(() => {
  socket = io();
  if (/* some condition */) {
    socket.emit("join", {
      // some code...
    });
    // socket open on user join
    return () => {
      socket.disconnect();
    };
  }
}, []);

Issue:

The socket connection works as expected, but when the mobile device goes to sleep mode, the connection seems to be lost. I’ve tried implementing a solution, but I’m unsure about the best approach to keep the socket connection active during sleep mode.

Request for Help:

  1. What are the recommended strategies or best practices to maintain a
    socket connection when a mobile device goes into sleep mode?
  2. Are there specific configurations or events I should be aware of in
    Socket.IO to handle such scenarios?
  3. Any insights or code examples related to handling socket connections
    on mobile devices, especially in the context of mobile web applications?

Any assistance or guidance would be greatly appreciated. Thanks in advance!

How to disable the Daterangepicker default value?

How to disable the Daterangepicker default value? I used daterangepicker to create a property availability filter feature based on date range. Here, I have created code like this, but the problem is that daterangepicker displays the default date today. How to disable the default value?

<input type="text" id="dates" class="form-control filter-field" placeholder="Enter dates" aria-label="Dates">
    var dates = [];

    $(document).ready(function(){
        //filter by dates
        $('#dates').daterangepicker({
            defaultDate: null,
            opens: 'left',
            locale: {
                format: 'YYYY-MM-DD'
            }
        }, function(start, end, label) {
            dates = [start.format('YYYY-MM-DD'), end.format('YYYY-MM-DD')];
            filterProperty();
        });
    })

Thank you

How to change what the textfields based on what the user inputs?

I am new to JavaScript and need to create an acceleration formula calculator. I need to first ask what variable the user would like to solve for in the acceleration formula (a=(v-u)/t) and then change textfields based on what the user inputs. Please let me know ASAP if you can help!

Here is what I have been working on…

Variable Solver

function showInputs() {
  var variable = document.getElementById("variable").value;

  if (variable === "v") {
    document.getElementById("u-input").style.display = "inline";
    document.getElementById("a-input").style.display = "inline";
    document.getElementById("t-input").style.display = "inline";
  } else if (variable === "u") {
    document.getElementById("v-input").style.display = "inline";
    document.getElementById("a-input").style.display = "inline";
    document.getElementById("t-input").style.display = "inline";
  } else if (variable === "t") {
    document.getElementById("v-input").style.display = "inline";
    document.getElementById("u-input").style.display = "inline";
    document.getElementById("a-input").style.display = "inline";
  }
}

Fix galaxy s23 {“meta”:{“success”: false, “message”:” [NullPointerException] null”}}

The error appeared after requesting samsung support

I need to secure device control from remote access and remove all account administrators and family links. I have many screenshots available and data to help secure my device. Hackers use philshing and imitate my device, possibly cloning. I have reached out to Samsung many times and received no solution. I am not a developer only a consumer, however I follow instructions, update and research apps that may assist me but without removal of remote devices and administrative controllers, I am powerless.

This MCQ is Asked University Exam in ReactJs Paper

Which of the following method is used to access the state of a component from inside of a member function?

A] this.prototype.stateValue

B] this,getState()

C] this.values

D] this.state

Please answer it with explaination because they said this.values is the answer and some of the websites also.

But according to me this.values does not exist in React at all.
I have done this code for understanding

import React, { Component } from "react";

class ClassBase extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
      message: "Hello",
    };
  }

  incrementCount = () => {
    this.setState((prevState) => ({
      count: prevState.count + 1,
    }));
    console.log("this.state " + this.state) // object
    console.log("this.values " + this.values) // undefined
    console.log("this.value " + this.value) // undefined

  };

  changeMessage = () => {
    this.setState({
      message: "Goodbye",
    });
  };

  render() {
    const { count, message } = this.state;



    return (
      <div>
        <h1>Count: {count}</h1>
        <button onClick={this.incrementCount}>Increment</button>
        <h1>Message: {message}</h1>
        <button onClick={this.changeMessage}>Change Message</button>
      </div>
    );
  }
}

export default ClassBase;

Merge Arrays by Index

I have one array with the current week like:

[
 {time: "Monday", value: 0},
 {time: "Tuesday", value: 0},
 {time: "Wednesday", value: 0},
 {time: "Thursday", value: 0},
 {time: "Friday", value: 0},
 {time: "Saturday", value: 0},
 {time: "Sunday", value: 0}
]

and another array with the current values from this week, e.g. for wednesday:

[
 {time: "Monday", value: 5},
 {time: "Tuesday", value: 10},
]

My Problem now is that I don’t know how to replace the two objects from the second array into the first array so that I have a result like this:

[
 {time: "Monday", value: 5},
 {time: "Tuesday", value: 10},
 {time: "Wednesday", value: 0},
 {time: "Thursday", value: 0},
 {time: "Friday", value: 0},
 {time: "Saturday", value: 0},
 {time: "Sunday", value: 0}
]

What does this mean: “constructor(…[configuration])?

In the aws-sdk-js-v3 I have the class CognitoIdentityClient with a constructor which expects a parameter, which I don’t understand:

export class CognitoIdentityClient extends __Client<
  __HttpHandlerOptions,
  ServiceInputTypes,
  ServiceOutputTypes,
  CognitoIdentityClientResolvedConfig
> {
  constructor(...[configuration]: __CheckOptionalClientConfig<CognitoIdentityClientConfig>) {
    const _config_0 = __getRuntimeConfig(configuration || {});
    [...]
    }
}

Why these 3 dots and the brackets? What does it mean?
I’m calling it currently like this, but it leads to unexpected behaviour:

new CognitoIdentityClient([myConfiguration]);

How can I fix my page rendering/refreshing issues with making a call to an API in React?

I have a very small task here. I just need to visualize the data from the given API to a line chart and then just add some decent styling. I am in the beginning stages here and just trying to ensure that my app will work first before I start with making the chart. However, I face very weird issues before even getting to issues with the chart. Given the following code:

import { useState, useEffect } from 'react';
import axios from 'axios';

function App() {
 const [weather, setWeather] = useState([]);
 const [loading, setLoading] = useState(true);

 useEffect(() => {
   axios.get('https://api.open-meteo.com/v1/forecast?latitude=65.01&longitude=25.47&hourly=temperature_2m')
     .then(response => {
       setWeather(response.data);
       setLoading(false);
     })
     .catch(error => {
       console.error(error);
       setLoading(false);
     });
 }, []);

 return (
   <div>
     {loading === true && !weather ? <p>Loading weather data from API. Please wait.</p> : null}
     <h1>Weather</h1>
     {console.log(weather)}
   </div>
 );
}

export default App;

I can refresh the page as many times as I like and component always re-renders. However, after making even the smallest changes, such as:

import { useState, useEffect } from 'react';
import axios from 'axios';

function App() {
  const [weather, setWeather] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    axios.get('https://api.open-meteo.com/v1/forecast?latitude=65.01&longitude=25.47&hourly=temperature_2m')
      .then(response => {
        setWeather(response.data);
        setLoading(false);
      })
      .catch(error => {
        console.error(error);
        setLoading(false);
      });
  }, []);

  const hourlyTemperaturesOneWeek = weather.hourly.temperature_2m;
  const hoursOneWeek = weather.hourly.time;

  return (
    <div>
      {loading === true && !weather ? <p>Loading weather data from API. Please wait.</p> : null}
      <h1>Weather</h1>
      {weather ? (
        <div>
      <p>Temperatures: {hourlyTemperaturesOneWeek}</p>
      <p>Hours: {hoursOneWeek}</p>
        </div>
      ) : null}
    </div>
  );
}

export default App;

This will be fine upon saving the file. However, upon page refresh, it breaks and I receive “weather.hourly” is undefined. In order for the page to work again at all, I must revert it to the previous code. This is very frustrating and I have searched online for the issue and tried a few solutions, but nothing has worked for my page. Any help would be highly appreciated. I’m hoping and thinking that it is something very simple that somebody would probably see in a flash. Asking AI also didn’t result in anything useful. Thanks in advance for anybody that has a good solution 🙂

P.S. Not sure if it is worth mentioning, but I also used Vite for setup. In addition, I am wanting to use either Highcharts, Chart.js, or react-chartjs-2, but I am also open to other suggestions, if anybody has some.

How to use different HTTP GET request in PrimeVue Datatable

I need to use different GET requests to display in my Datatable. Both come from different tables of the Database using different requests. I’m lost of what i have to do to make this work. I know i’m using different values in the :value of the Datatable. The values that i want to show is the Package and Page.

<DataTable :value="gridData" :paginator="true" :rows="50" :rowHover="true" :loading="loading" @page="scrollUp()"
               paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
               :rowsPerPageOptions="[15,25,50]" :autoLayout="true"
               selectionMode="single" dataKey="id"
               currentPageReportTemplate="Mostrando {first} até {last} de {totalRecords} Registros"
               :filters="filters"
               class="p-datatable-customers p-datatable p-component p-datatable-hoverable-rows"
               @row-select="onRowSelect">
        <div class="p-datatable-header">
            <div class="table-header">
                Orgs
                <span class="p-input-icon-left">
                <i class="pi pi-search"></i>
                <InputText v-model="filters['global']" placeholder="Global Search"/>
                &nbsp;&nbsp;&nbsp;&nbsp;
                <Button label="Novo" icon="pi pi-plus" iconPos="right" @click="goToNew"/>
                </span>
            </div>
        </div>
        <template #empty>
            Empty
        </template>
        <template #loading>
            load
        </template>
        <Column field="name" header="Name" headerClass="headerClass" bodyClass="bodyClass" :sortable="true"
                filterMatchMode="contains">
            <template #body="slotProps">
                {{slotProps.data.name}}
            </template>
        </Column>
        <Column field="trade_name" header="Trade" headerClass="headerClass" bodyClass="bodyClass" :sortable="true"
                filterMatchMode="contains">
            <template #body="slotProps">
                {{ slotProps.data.trade_name }}
            </template>
        </Column>
        <Column field="created_date" header="Date" headerClass="headerClass" bodyClass="bodyClass" :sortable="true"
                filterMatchMode="contains">
            <template #body="slotProps">
                {{ dateHourFormat(slotProps.data.created_date) }}
            </template>
        </Column>
        <Column field="name" header="Package" headerClass="headerClass" bodyClass="bodyClass" :sortable="true"
                filterMatchMode="contains">
            <template #body="slotProps">
                {{ slotProps.data.name }}
            </template>
        </Column>
        <Column field="file_name" header="Page" headerClass="headerClass" bodyClass="bodyClass" :sortable="true"
                filterMatchMode="contains">
            <template #body="slotProps">
                {{ slotProps.data.file_name }}
            </template>
        </Column>
    </DataTable>
 getAll() {
                this.customerService.getAll()
                    .then((response) => {
                        this.gridData = response;
                    }).catch((error) => {
                    console.log(error);
                })
            },
            getPackage() {
                this.operationPackage = []
                this.operationPackageService.getAllOperationPackages()
                    .then((response) => {
                        this.operationPackage = response;
                    }).catch((error) => {
                    if (error.response && error.response.data && error.response.data.details) {
                        this.$toast.add({
                            severity: 'error',
                            summary: error.response.data.details,
                            life: 5000
                        });
                    } else {
                        this.$toast.add({
                            severity: 'error',
                            summary: 'N',
                            life: 5000
                        });
                    }
                });
            },
            getPage() {
                this.operationPage = []
                this.operationPackageService.getAllHtmlFiles()
                    .then((response) => {
                        this.operationPage = response;
                    }).catch((error) => {
                    if (error.response && error.response.data && error.response.data.details) {
                        this.$toast.add({
                            severity: 'error',
                            summary: error.response.data.details,
                            life: 5000
                        });
                    } else {
                        this.$toast.add({
                            severity: 'error',
                            summary: 'N',
                            life: 5000
                        });
                    }
                });
            },

I tried to use the same :value for the GET requests, but it did not worked. It shows the first value that is loaded in the mounted. If loads getAll first, it show the values, but if loads getPackage, it shows the package values.

Make custom hook be dependent on React Query hook

I have a problem with using my custom hook after using a useQuery hook.

Catalogue.jsx

import { Box, Spinner } from "@chakra-ui/react";
import ProductPage from "../../components/Products/ProductPage";
import useBeers from "../../hooks/useBeers";
import useProductData from "../../hooks/useProductData";

const Catalogue = () => {
  const { data: products, isLoading } = useBeers();

  const productData = useProductData(products);

  if (isLoading) return <Spinner />;

  return (
    <Box>
      <ProductPage productData={productData} />
    </Box>
  );
};

export default Catalogue;

So, i want my useProductData execute only if have already got products from useBeers.
useBeers.js

import { useQuery } from "@tanstack/react-query";
import axios from "axios";

const useBeers = () =>
  useQuery({
    queryKey: ["beer"],
    queryFn: () =>
      axios.get("localhost:3001/api/beers").then((response) => response.data),
  });

export default useBeers;

useProductData.js

import { useState } from "react";

function useProductData(products) {
  const brands = products.map(({ id, brand }) => ({
    id,
    brand,
  }));
  const prices = products.map((item) => item.price);
  const min = Math.min(...prices);
  const max = Math.max(...prices);

  const title = "Crowlers"; // TODO

  const uniqueBrands = brands.filter(
    (item, index, self) =>
      index === self.findIndex((t) => t.brand === item.brand)
  );

  const [filteredValues, setFilteredValues] = useState([min, max]);
  const [checkedBrands, setCheckedBrands] = useState({});

  const brandFilterData = { uniqueBrands, checkedBrands, setCheckedBrands };
  const priceFilterData = { min, max, filteredValues, setFilteredValues };

  const isVoucher = products.every((product) =>
    product.name.includes("Voucher")
  );

  return {
    filteredValues,
    checkedBrands,
    products,
    title,
    brandFilterData,
    priceFilterData,
    isVoucher,
  };
}

export default useProductData;

I tried changing the order of lines to execute useProductData only if !isLoading like this but it didn`t work as i expected, i had an error:
React Hook “useProductData” is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?

const { data: products, isLoading } = useBeers();

  if (isLoading) return <Spinner />;

  const productData = useProductData(products);

function name not available in production build in vite global import

I’m using vite global import feature to register some functions in globalProperties in vue 3 app to achive global $filters array in main.ts.

It works propely in development time but after production build func.name always is empty string and dose not contain function name.

Object.values(import.meta.glob<Function[]>('./common/filters/*.filter.ts', 
{ eager: true, import: 'default' }))
  .forEach(filters => filters.forEach(func => app.config.globalProperties.$filters[func.name] = func))

app.mount('#app')

currency.filter.ts

const filters: Function[] = [
  function currency(value: string) {
    if (!value)
      return value

    return `${value.toLocaleString()}$`
  },
]
export default filters

and finally I can use them inside vue components like filters in vue 2:

{{ $filters.currency(item.price) }}

how can solve this issue or is there better way to import all functions inside files in a directory and register in globalProperties

console log of app.config.globalProperties.$filters in dev:

{
   currency: Æ’ currency(value)
   length:1
   name:"currency"
}

Array of Numbers can be seen in the logs of both frontend and backend yet it is not saved in the database

I am trying to replicate google’s Backup Codes system by generating 4 random 8 digit numbers.

for(let i = 0; i < 4; i++) {
      let backendCode = Math.floor(Math.random() * (99999999 - 10000000 + 1) + 10000000);
      backendCodes.push(backendCode);
    }

Using a Backend Service to post to the backend.

constructor(private http: HttpClient) { }

  signUpUser(email: string, password: string, backendCodes: number[]) {
    const url = "http://localhost:3000/signup/api"
    const body = { email, password, backendCodes };
    console.log(body); // Add this line to log the request body
    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });

    this.http.post(url, body, { headers }).subscribe({
      next: value => console.log(value),
      error: error => console.log(error),
      complete: () => console.log("Complete")
    });
  }

Then saving it in the database (MongoDB).

app.post("/signup/api", async (req, res) => {
  const { email, password, backupCodes } = req.body;
  console.log(req.body); 
  try {
    const newUser = new User({
      email: email,
      password: password,
      backupCodes: backupCodes,
    });

    await newUser.save();
    console.log("Successful");
    res.status(200).json({ message: "User signed up successfully" });
  } catch (err) {
    console.log("Error: ", err);
    res.status(500).json({ error: "Internal Server Error" });
  }
});

What was I expecting

I was expecting everything to be saved, but saw that the backupCodes was empty.
As shown here

What I’ve tried

I tried logging the output before posting to the backend and before saving the data to the database

Frontend

signUpUser(email: string, password: string, backendCodes: number[]) {
    const url = "http://localhost:3000/signup/api"
    const body = { email, password, backendCodes };

    console.log(body); // Test before post

    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });

    this.http.post(url, body, { headers }).subscribe({
      next: value => console.log(value),
      error: error => console.log(error),
      complete: () => console.log("Complete")
    });
  }

Backend

app.post("/signup/api", async (req, res) => {
  const { email, password, backupCodes } = req.body;

  console.log(req.body); // Test before saving to Database

  try {
    const newUser = new User({
      email: email,
      password: password,
      backupCodes: backupCodes,
    });

    await newUser.save();
    console.log("Successful");
    res.status(200).json({ message: "User signed up successfully" });
  } catch (err) {
    console.log("Error: ", err);
    res.status(500).json({ error: "Internal Server Error" });
  }
});

Here is the screenshots of the result:-

Frontend Console Log and
Backend Console Log

Here is my Schema, if this is the issue:

const userSchema = new mongoose.Schema({
  email: String,
  password: String,
  backupCodes: [Number],
});

How can web server push data to browser? [closed]

I used a web application product in a work setting pre 2010, which had about 5 browsers accessing the application at the same time.

The product allowed one user to press a button in the app which caused a document to display on the browsers of the other 4 users.

From my basic understanding of website programming, I can’t understand how a web server could “push” data to a browser.

I’m wondering pre-2010 what technology this would have been. I noticed that Web Push API has only been around since about 2015, so it can’t have been that.

Would there have been client side javascript that was polling the web server every second to see if there was a notification?

Best alternatives of Cypress Dashboard

I am a beginner in a Cypress. I am using Cypress with JavaScript in my project.

Now, I want to generate a report. There are different options available like Cypress Dashboard, Mochawesome, sorry-cypress, current, and cypress-split. Each has its advantages and disadvantages. So I am confused about which I have to use. I found a feature, disadvantages and advantages of Dashboard, sorry-cypress and Currents. But I am unable to find the same for mochawesome and cypress-split in enough quantity. That’s why I can’t decide which I have to use.

The problem with using Cypress Dashboard is, it uses Cypress Cloud and saves all recordings there. Is there any option for it? How can I handle it?

Thanks!

How can I separate categories when writing a new article in wordpress?

I have more than 150 categories and subcategories, and I need this number due to the nature of my site, but I am facing a problem in searching for the appropriate category while writing the article. Is there a way to hide the subcategories, so that the subcategories do not appear until after choosing the main category?

I am use these and include it in JavaScript/jQuery file:

jQuery(document).ready(function($) {
    // Hide all subcategories initially
    $('#categorychecklist input[type="checkbox"]').each(function() {
        if ($(this).parent().hasClass('children')) {
            $(this).hide();
        }
    });

    // Show subcategories when a main category is selected
    $('#categorychecklist input[type="checkbox"]').change(function() {
        if ($(this).parent().hasClass('category')) {
            var mainCatID = $(this).val();
            $('input[type="checkbox"][value^="' + mainCatID + '"]').show();
        }
    });
});

Then paste the provided code in a .js file (e.g., hide-subcategories.js).
Finally, I added the following code to the file functions.php:

function enqueue_hide_subcategories_script() {
    wp_enqueue_script('hide-subcategories', get_template_directory_uri() . '/js/hide-subcategories.js', array('jquery'), '1.0', true);
}
add_action('admin_enqueue_scripts', 'enqueue_hide_subcategories_script');

But this did not work and there was no change