What’s the best way of merging fetched data from API? React JS [closed]

What would be the best way to do on merging fetch data from different API?

helperFunction.js

async function getRequestWithAuth(url, token) {
    return fetch(url,
        {
            method: 'GET',
            mode: 'cors',
            headers: {
                'Content-Type': 'application/json',
                'authorization': `bearer ${token}`
            },
            redirect: 'follow'
        })
        .then(response => {
            if (response.ok) {
                return response.json();
            } else {
                console.warn(response)
                return null;
            }
async function getSearchResults(requestParams, startDate, endDate, token) {
    const request = new URLSearchParams({
       //request details
    });
    return getRequestWithAuth(`api/reviews?${request}`, token);
}

This is the other one that I want to add.

async function getSearchResults2(requestParams, startDate, endDate, token) {
    const request = new URLSearchParams({
       //request details
    });
    return getRequestWithAuth(`api/something?${request}`, token);
}

Would it be possible to combine the getSearchResult and getSearchResults2?

What I did here was

sync function getSearchResults(requestParams, startDate, endDate, token) {
    const request = new URLSearchParams({
       //request details
    });
    return getRequestWithAuth(`api/reviews?${request}`, token) & getRequestWithAuth(`api/process?${request}`, token);

Why can’t setTimeout be extended even when referring to the timeout ID?

I have multiple commands in discord.js v14 that give the user the same role for different amounts of time (temporary role). /pug30 is for 30 minutes and /pug1 is for 1 hour for example. Why is it that I can reduce the length of time if I use /pug1 and then /pug30 right after, but can’t extend it if I use /pug30 and then /pug1? How do I get the timer to extend?

Also, the log always prints “user does not have role” no matter what so for some reason (maybe because each command is a separate interaction?), my code only executes the “if” part of the if statement.

const { CommandInteraction, SlashCommandBuilder, EmbedBuilder } = require('discord.js');


// Object to store timeouts for each user
var userTimeouts = {};


module.exports = {
    data: new SlashCommandBuilder()
        .setName("pug1")
        .setDescription("Adds the user to the PUG Queue for 1 hour."),
          async execute(interaction) {
            const user = interaction.user;
            const role = interaction.guild.roles.cache.find(r => r.name == 'PUG Queue');
            //const role = interaction.guild.roles.cache.get("628292255785943062");
            const member = await interaction.guild.members.fetch(user);

            if (!member.roles.cache.has(role)) {
              console.log('user does not have role')
              member.roles.add(role);

            // Clear previous timeout, if any
              clearTimeout(userTimeouts[user]);
              userTimeouts[user] = null;

            // Set new timeout and store it in userTimeouts
              userTimeouts[user] = setTimeout(() => {
                  member.roles.remove(role);
                  delete userTimeouts[user]; // Cleanup timeout reference
              }, 3600000);

              const embed = new EmbedBuilder()
                  .setTitle(" ")
                  .setDescription(`Added ${interaction.user} to the PUG Queue for 1 hour.`)
                  .setColor(0x4169E1);

              await interaction.reply({ embeds: , ephemeral: false });

            } else {
                console.log('user has the role')
                // Clear previous timeout
                clearTimeout(userTimeouts[user]);
                userTimeouts[user] = null;

                // Set new timeout
                userTimeouts[user] = setTimeout(() => {
                    member.roles.remove(role);
                    delete userTimeouts[user]; // Cleanup timeout reference
                }, 3600000);

                const embed = new EmbedBuilder()
                    .setTitle(" ")
                    .setDescription(`Added ${interaction.user} to the PUG Queue for 1 hour.`)
                    .setColor(0x4169E1);
                    
                await interaction.reply({ embeds: , ephemeral: false });
            }
    }
}

Prisma Nextjs Getting undefined session before getting to submitData on form

I am making an edit function for objects in my postgres database. I am using nextauth as well for my session. When I try to submit form data (like updating the fields defined in my schema), I get an error, client_fetch_error undefined Posting to the database works just fine. (By the way I am new to web development as a whole)

I am using next version 12.1.2 and next-auth 4.24.6

Apologies if I didn’t include some information that would be useful, ask away if I left out anything.

Here is the route that has all of the code for the edit page,

import React, { useState } from "react";
import { GetServerSideProps } from "next";
import ReactMarkdown from "react-markdown";
import Layout from "../../../components/Layout";
import Router from "next/router";
import { PostProps } from "../../../components/Post";
import prisma from '../../../lib/prisma'
import { useSession } from "next-auth/react";

export const getServerSideProps: GetServerSideProps = async ({ params }) => {
  const course = await prisma.course.findUnique({
    where: {
      id: String(params?.id) ,
    },
    include: {
      author: {
        select: { name: true, email: true,},
      },
    },
  });
  return {
    props: course,
  };
};

const Post: React.FC<PostProps> = (props) => {
  const { data: session, status } = useSession();
  if (status === 'loading') {
    return <div>Authenticating ...</div>;
  }
  const userHasValidSession = Boolean(session);
  const postBelongsToUser = session?.user?.email === props.author?.email;
  let title = props.title;
  
  title = `${title}`;
  
  const [desc, setDesc] = useState("");
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [number, setPhone] = useState("");
  const [courseid, setCourseid] = useState("");

  const submitData = async (e: React.SyntheticEvent) => {
    console.log("got to submit")
    e.preventDefault();
    try {
      const body = { title, courseid, name, email, number, desc };
      await fetch(`/api/post/${props.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      await Router.push("/");
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <Layout>
      <div>
        <h2>{title}</h2>
        <p>By {props?.author?.name || "Unknown author"}</p>
        <ReactMarkdown children={props.desc} />
        <form onSubmit={submitData}>
          
          <h3>Course ID</h3>
          <input
            autoFocus
            onChange={(e) => setCourseid(e.target.value)}
            placeholder="e.g. Math 301"
            type="text"
            value={courseid}
          />
          
          <h3>Teacher's Name</h3>
          <input
            autoFocus
            onChange={(e) => setName(e.target.value)}
            placeholder="Teacher Name"
            type="text"
            value={name}
          />
          <h3>Email</h3>
          <input
            autoFocus
            onChange={(e) => setEmail(e.target.value)}
            placeholder="Email"
            type="text"
            value={email}
          />
          <h3>Phone</h3>
          <input
            autoFocus
            onChange={(e) => setPhone(e.target.value)}
            placeholder="Number"
            type="text"
            value={number}
          />
       
          <textarea
            cols={50}
            onChange={(e) => setDesc(e.target.value)}
            placeholder="Important Notes"
            rows={8}
            value={desc}
          />
           {userHasValidSession && postBelongsToUser && (
          <button type="submit">Edit</button>
        )}
          <a className="back" href="#" onClick={() => Router.push("/")}>
            or Cancel
          </a>
          
        </form>

      </div>
      
    </Layout>
  );
};

export default Post;

Is there a way to see exactly what objects the GC is recycling during “Major GC” events in the profiler?

I’m currently writing an Electron/Typescript based game with a render loop. I’ve been developing it for about a year but have only just discovered that the game has horrible memory issues if the render loop goes on too long (while profiling performance, I eventually see “Major GC” events that cause lag and interrupt/skip frames. I believe there must be an object that’s not being correctly managed somewhere (I’ve tried to adhere to high performance best practices, memory pooling, no new allocations during render, etc.)

Is there any way that I can see exactly what the GC is recycling during these frames so I can isolate the leak?

I’ve tried profiling memory, but this only seems to show new allocations rather than what’s being deallocated (I create large pools of objects at the start of rendering, and I guess some of them are not being recycled properly). There doesn’t seem to be any way through the performance tab to dig any deeper into what’s actually happening in the major GC frames. I’ve tried console logging out every allocation I think I’m making and counting when they’re returned to the pool, but nothing obvious is emerging.

React-Redux could not find react-redux context value when using useSelector

i created a store and authreducer and every thik work as expected
but when i add the use sellector in app .js i got this err

ERROR  Error: could not find react-redux context value; please ensure the component is wrapped in a <Provider>  

(I have tried using useSelector in other files without any errors. )

enter image description here

import { ApolloClient, ApolloProvider } from "@apollo/client";
import { Provider, useSelector } from "react-redux";
import Navigation from "./navigation";
import Navigation2 from "./navigation2";
import { store } from "./src/Redux/store";
import InMemoryCacheFct from "./src/apolloClient/InMemoryCache";

export default function App() {

  const user = useSelector(state => state.auth.isAuthenticated);// the err is when i add this line even he works in other files

  const client = new ApolloClient({
    uri: ".......serverUrl",
    cache: InMemoryCacheFct(),
    queryDeduplication: true,
  });

  return (
    <ApolloProvider client={client}>
      <Provider store={store}>
        {user ? <Navigation /> : <Navigation2 />}
      </Provider>
    </ApolloProvider>
  );
}

TypeError: ollama.chat is not a function in Node.js with the ollama module

I’m working on a Node.js project where I’m trying to use the ollama (ollama-js) module. However, when I call the async function chatWithLlama() (which has ollama.chat() inside), I encounter the following error:

TypeError: ollama.chat is not a function

Here’s the relevant code snippet:

const ollama = require('ollama');

async function chatWithLlama() {
  try {
    const response = await ollama.chat({
      model: 'llama3',
      messages: [{ role: 'user', content: 'Why is the sky blue?' }],
    });
    console.log(response.message.content);
  } catch (error) {
    console.error('Error:', error);
  }
}

chatWithLlama();

I have made sure that the ollama module is properly installed using npm and included in the package.json file and node_modules directory. I also have Ollama running on my Mac, with llama3 already installed. How can I resolve this issue?

How can I make my popup appear fully visible on Google map with React?

What I’m doing:

  1. I’m using @react-google-maps/api with React, rendering some markers + popup div.
  2. I’m using OverlayView for the markers on the map.
  3. When I click a pin – I show an info div for that pin.
  4. The info popup div is currently a Box element from ChakraUI, that can change if need be. But it shouldn’t make any difference.

What I would like:

  • I want to ensure that the popup div is fully visible, not cut off, depending on the position of the map relative to its bounds.

I would be happy to have either of the following:

  • Move the map so the info window is fully visible.
  • Position the info window differently so that it’s fully visible.

I’ve not had any success yet, just can’t find a way to do it. Any help would be appreciated.

Here’s the React markup, showing how I’m rending the marker with the price, and the info popup

  return (
    <>
      <OverlayView position={props.position} mapPaneName={OverlayView.OVERLAY_MOUSE_TARGET}>
        <Box>
          <Card                      
            id={`marker-${props.markerIndex}`}
            border={'1px solid rgb(221, 222, 224)'}
            borderRadius={'24px'} 
            width={'max-content'}  
            onClick={props.onClick}  
            color={ (props.isSelected || props.isHoveringResult) ? 'white': 'black' }     
            backgroundColor={ (props.isSelected  || props.isHoveringResult) ? 'black': 'white' }>
            <CardBody padding={'8px'} textAlign={'center'}> 
              <Text fontSize={'14px'} fontWeight={'bold'}>
                {priceStr}
              </Text>
            </CardBody>
          </Card>


          {/* Desktop display item sticks to map and moves. */}
          { props.isSelected && 
            <Box 
              id={`markerPopup-${props.markerIndex}`}
              onClick={() => {
                event.stopImmediatePropagation();
              }}
              width={{ base: '100%', sm: '400px'}}
              position={'relative'} marginTop={'16px'}
              zIndex={'tooltip'}>
              <HotelSearchResultDisplayMapItem />
              <Box pos={'absolute'} right="8px" top="8px" cursor={'pointer'}>
                <FontAwesomeIcon             
                icon={solidCircleXMark} 
                size='3x'
                color='white'
                />
              </Box>         
            </Box>
          }        
        </Box>
      </OverlayView>
    </>
  );

Here’s what it looks like so far:

You can see that because my marker is lower down, the popup is cut-off.

enter image description here

How many series does echart support for line graph

I have an array of user objects. Each user has an array of dates. For each date there is an “activity counter”. I would like to output this information as a line graph using echart.js, where the x axis is the date, y is the activity bar, the line on the graph is the individual user.
I see big performance problems with more than 200 users on the graph. I don’t understand if echart really can’t render 200 lines well or if the problem is in my data?
I transfer data for each user as a separate series:

const options = {
  //
  //...some basic settings,
  series: [
    {
      "type": "line",
      "data": "0", "0", "7", ...other ~30 activity-points..., "3"
    },
    {
      "type": "line",
      "data": "15", "43", "17", ...other ~30 activity-points..., "6"
    },
    ...other ~200 data-objects
  ]
}
myChart.setOption(option);

I have now reproduced the example locally to encapsulate the environment, on a blank page, just a script with a graph, with minimal settings. And I get performance problems when trying to interact with a graph: mouseMove causes huge rendering lags. The more settings you make (for example, add a stack option to display a line graph), the worse it gets.

Expo error: Uncaught Error: java.lang.Exception: Failed to load all assets

When I start expo server using npx expo start -c server starts. My mobile and laptop are also connected on the same network. Now when I scan expo qr code through expo go in mobile, it displays error saying Uncaught error: java.lang.Exception: Failed to load all assets sometimes displays timeout error. What’s the issue? It’s fresh project just installed everything.

In package.json file as per the documentation i’ve set

{
   .....
   "main": "expo-router/entry",
   .....
}

and project folder structure like

......
app
  _layout.jsx
assets
node_modules
.....
......

Getting nth child count from a div class using javascript

I am trying to find count or nth child from here. As per below I should get 3 and dynamically it will change based on number results.

<div class="result-container list-layout-container">
   <div class="list-layout">Result1</div>
   <div class="list-layout">Result2</div>
   <div class="list-layout">Result3</div>
</div>

so, I used the below function to get the length 3 but I am not getting it instead I am getting undefined or 0.
Please suggest.

var len = document.getElementsByClassName('result-container').length;
console.log("Length count is", len);

How to strip the digit from a string

I am trying to extract a number from a string using regex for javascript.

Test cases

value[0]        ---> 0
value[1]        ---> 1
object2value[0] ---> 0
object90        ---> no match

i tried using ([w]+)*?[d] but it give

value[0]        ---> value[0]
value[1]        ---> value[1]
object2value[0] ---> object2value[0]
object90        ---> no match

how i can achieve this.

How to check if a user’s answer is valid and re ask the question if it is not in javascript?

I am making a choose your own adventure story game and I am trying to take a user’s input and see whether they typed “n” or “y” and if they didn’t re-ask the question. Currently, when typing in something other than “y” or “n” the code works and re-asks the question.

However, when the user inputs “n” I want the code to update the variable choice to false and run code that tells the user they have failed and asks them if they would like to try again. This code does not run and instead continues the for loop.

I assume that this code also does not work when I try to update the variable restartGame.

I am super new to coding and this is the first proper code that I have made myself outside of my highschool class instruction so any help would be amazing. 🙂

Here is the code that I made:

let food = null;

let storyParts = ["You wake up in a dark hole and an alien approaches you. His name is Tony.",
"You board Tony's ship and you see a goblin in the corner. Tony tells you it doesn't bite.",
"The goblin is visibly shaken and bites off one of your fingers.", 
"Tony feels bad and offers you food.", 
"You eat the " + food]

let storyChoices = ["Do you board his ship? (Yes / No) ", 
"Do you pet the goblin? (Yes / No) ", 
"Spin for food? (Yes / No) ",
"Try again? (Yes / No) "]

let failStatements = ["Tony is disappointed in you. He was your father the whole time. Game over.", 
"Tony is upset. He asks you to leave. Game over."]

let foodOptions = ["pizza", "cupcake", "goblin soup", "finger", "pasta"]

function userInput(line) {
    while (1) {
        let answer = readLine(line);
        if (answer == "y") {
            break;
            return true;
        } else if (answer == "n") {
            break;
            return false;
        } else {
            println("Please type 'y' for yes and 'n' for no.");
        }
    }
}

for (let i = 0, len = storyParts.length; i < len; i++) {
    println(storyParts[i]);
    let choice = null;
    if (i == 0) {
        choice = userInput(storyChoices[0]);
    } else if (i == 1) {
        choice = userInput(storyChoices[1]);
    } else if (i == 4) {
        choice = userInput(storyChoices[2]);
    } else {
        
    }
    if (choice == false) {
        let restartGame = userInput(storyChoices[3]);
        if (restartGame == true) {
            i = -1;
            continue;
        } else if (restartGame == false) {
            i = len;
            break;
        } else {

        }
    }
}

The output is below. As you can see when I first type n it continues to the next part of the story when I want it to show the fail statement and ask if I would like to restart the story.

You wake up in a dark hole and an alien approaches you. His name is Tony.
Do you board his ship? (Yes / No) n
You board Tony's ship and you see a goblin in the corner. Tony tells you it doesn't bite.
Do you pet the goblin? (Yes / No) y
The goblin is visibly shaken and bites off one of your fingers.
Tony feels bad and offers you food.
You eat the null
Spin for food? (Yes / No) e
Please type 'y' for yes and 'n' for no.
Spin for food? (Yes / No) e
Please type 'y' for yes and 'n' for no.
Spin for food? (Yes / No) n

“How to Troubleshoot File Saving Issues When Uploading to Server?”

“Hello Community,

I’m currently working on a client-server application, and I’ve encountered an issue when uploading files to the server. It seems that when I upload a file, it’s not being saved with its original name, extension, or content. For instance, if I upload a file named ‘file.txt’ containing specific information, it’s saved on the server simply as ‘upload’, without retaining its original name, extension, or content.

Could anyone advise me on how to ensure that files uploaded to the server are saved with their original name, extension, and content intact? Any help on resolving this matter would be greatly appreciated.

Thank you!”

client

import socket
import os

HOST = 'localhost'
PORT = 5173

def subir_archivo(socket_cliente, nombre_archivo):
    socket_cliente.sendall(b"subir")
    socket_cliente.sendall(nombre_archivo.encode('utf-8'))

    with open(nombre_archivo, 'rb') as archivo:
        contenido = archivo.read()
    socket_cliente.sendall(contenido)

    print("Archivo enviado al servidor:", nombre_archivo)

def descargar_archivo(socket_cliente, nombre_archivo):
    socket_cliente.sendall(b"descargar")
    socket_cliente.sendall(nombre_archivo.encode('utf-8'))

    respuesta = socket_cliente.recv(1024)
    if respuesta == b"EXISTE":
        contenido = socket_cliente.recv(1024)
        with open(nombre_archivo, 'wb') as archivo:
            archivo.write(contenido)
        print("Archivo descargado:", nombre_archivo)
    else:
        print("El archivo no existe en el servidor.")

opcion = input("¿Qué acción deseas realizar? (subir/descargar): ").lower()

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as cliente:
    cliente.connect((HOST, PORT))

    if opcion == 'subir':
        nombre_archivo = input("Ingrese el nombre del archivo que desea subir: ")
        subir_archivo(cliente, nombre_archivo)
    if opcion == 'descargar':
        nombre_archivo = input("Ingrese el nombre del archivo que desea descargar: ")
        descargar_archivo(cliente, nombre_archivo)

server

import socket
import hashlib
import threading

HOST = "localhost"
PORT = 5173

def receive_file(client_socket):
    # Receive the file name from the client
    file_name = client_socket.recv(1024).decode()
    
    # Receive the file content from the client
    file_content = client_socket.recv(1024)
    
    # Receive the hash of the file from the client
    received_hash = client_socket.recv(1024).decode()

    # Calculate the hash of the received file content
    calculated_hash = hashlib.sha256(file_content).hexdigest()

    # Write the received file content to a file
    with open(file_name, 'wb') as file:

        # Check if the calculated hash matches the received hash
        if calculated_hash == received_hash:
    
            # Write the file content to the file
            with open(file_name, 'wb') as file:
                file.write(file_content)
            print(f"File '{file_name}' received and saved successfully.")
            # Send acknowledgment to the client
            client_socket.send("ACK".encode())

def handle_client(client_socket):
    # Call the receive_file function to handle file receiving
    receive_file(client_socket)
    # Close the client socket
    client_socket.close()

def main():
    # Create a server socket
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Bind the server socket to the specified host and port
    server.bind((HOST, PORT))
    # Listen for incoming connections
    server.listen()
    print("Server waiting for connections...")

    while True:
        # Accept a client connection
        client_socket, client_address = server.accept() 
        print(f"Connection accepted from {client_address}")
        
        # Create a new thread to handle the client
        client_thread = threading.Thread(target=handle_client, args=(client_socket,))
        client_thread.start()

main()

````