GET request to API Id not found, request to entire API works

Basically I’ve been stuck for days unsure of what the error is. My get request for all books works

export const getBooks = async () => {
  try {
      const response = await api.get('/books')
      return response.data
  } catch (error) {
      throw error
  }
}

Trying to get an individual book fails to grab it by the id

export const getBook = async id => {
  try {
    const response = await api.get(`/books/${id}`)
      return response.data
  } catch (error) {
      console.log("This is the problem")
  }
}

I can see and console the array of objects in localhost:3000/api/books in my app, but get CANNOT GET if I try to see a specific object by index number i.e localhost:3000/api/books/1 or localhost:3000/api/books/434r47r3g738384 ( by the specific :id)

This is the error when I inspect.

Request URL: http://localhost:3000/api/books/62bdf9227dfc85a4a55fd4c7
Request Method: GET
Status Code: 404 Not Found
Remote Address: [::1]:3000
Referrer Policy: strict-origin-when-cross-origin

How can call function what contain true / false value?

Hello i start upgrading my extension for on / off client side, but i have problem with call function ( i mean enable / dissable ) can you help me please fox this little problem? Thank you

Extension work, i have problem with individual direct calling, example is in code, i need primary work with >> var Button_two = true; <<

const CSS_PROGRAM = [
    'color: yellow;',
    'background: black;',
    'font-size: 15px;',
    'border: 1px solid red;',
].join(';');

const CSS_EXISTENCE = [
    'color: red;',
    'background: yellow;',
    'font-size: 15px;',
    'border: 1px solid red;',
    'font-weight: bold;',
].join(';');

(function () {
var tlačítko1;
var tlačítko2;



    chrome.storage.sync.get(function(data) {
        tlačítko1 = data.tlačítko1;
        tlačítko2 = data.tlačítko2;
        if (tlačítko1) {
            console.log('%c TOGGLE BUTTON 1 %c ZAPNUTO ', CSS_PROGRAM, CSS_EXISTENCE)
            omg();
        }else{
            console.log('%c TOGGLE BUTTON 1 %c VYPNUTO ', CSS_PROGRAM, CSS_EXISTENCE)
        }
        if (tlačítko2) {
            console.log('%c TOGGLE BUTTON 2 %c ZAPNUTO ', CSS_PROGRAM, CSS_EXISTENCE)
            var Button_two = true;
        } else {
            console.log('%c TOGGLE BUTTON 2 %c VYPNUTO ', CSS_PROGRAM, CSS_EXISTENCE)
            var Button_two = false;

        }
    });


})();




function omg() {
    alert("Im alive kurva nIm function fa** bi**")
}

(function () {
    if (!Button_two) return;
    alert("!Button_two nnIm alive kurva nIm function fak** bi**")

})();

React Context is not updating correctly

I’m building an application using React and Typescript and I want to auth users and keep the authenticated user in the context, but my context is not updating correctly.

Edit: After inspection it seems like the context is being updated correctly, but the UI is not being re-rendered and I dont know why.

AuthProvider.tsx

import { createContext, useState, Dispatch, SetStateAction, useMemo } from "react";

interface AuthContextProps {
  auth?:{}, // Refactor this for a authInterface with correct keys
  setAuth?: Dispatch<SetStateAction<{} | null>>
}

export const AuthContext = createContext<AuthContextProps>({
  auth: null,
  setAuth: (prevState: SetStateAction<{} | null>) => prevState
})

export const AuthProvider = ({ children }:any) => {
  const [auth, setAuth] = useState<AuthContextProps>(undefined)
  const value = useMemo(() => ({ auth, setAuth }), [auth, setAuth])
  
  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  )
}

which is used in App.tsx I think correctly

function App() {
  return (
    <AuthProvider>
      <Router>
        <Routes>
          <Route path="/" element={<LoginRoute />} />
          <Route element={<PrivateRoute />}>
            <Route path="home" element={<HomeRoute />} />
          </Route>
        </Routes>
      </Router>
    </AuthProvider>
  )
}

export default App

The PrivateRoute.tsx is just a wrapper that should handle rendering correct routes (where is auth required)


export const PrivateRoute = () => {
  const fallbackRoute = "/";

  const {auth} = useContext(AuthContext);

  return auth ? (
    <Navigate to="/home" />
  ) : (
    <Navigate to={fallbackRoute} />
  );
};

and when login form is submitted, I (try to) update the state like this (the body is a dummy response from auth server)

setAuth({
      status: 200,
      token: "someTokenDoesntMatter",
      user: {
        id: 1,
        email: "[email protected]",
        f_name: "Jan",
        l_name: "Novak",
        username: "jan.novak"
      }
    })

Which I think passes correctly, because when I log auth object into the console, it prints the correct data.

console.log() of the auth object

But the endpoint route keeps unchanged, even though I thought that in PrivateRoute.tsx I said that if the auth object exists (is not null or undefined) the children components (routes) will be rendered since the component, but that doesnt happen.

Any help is very much appreciated and pardon me if I missed something banal and this is a stupid question.

ReactJS: Why isn’t my draggable pop-up functional component staying under the mouse when dragged?

Hi everyone & thanks in advance for your help!

I am working on a custom draggable pop-up functional component, but the dragging isn’t working as intended and the div does not follow under the mouse.

I had some extra logic in there to handle the x & y offset of the mouse inside the div, but I removed that to first debug why the dragging isn’t working properly.

import React, {useState} from 'react';
import './DraggablePopup.css';

const DraggablePopup = () => {
    const [isDragging, setIsDragging] = useState(false);
    const [styles, setStyles] = useState({});

    const handleDragStart = (e) => {                
        console.log('Drag Start');
        setIsDragging(true);        
    }

    const handleDragging = (e) => {        
        if( isDragging ) {
            let left = e.screenX;
            let top = e.screenY;
            setStyles({
                left: left,
                top: top
            });
        }
    }

    const handleDragEnd = () => {
        console.log('Drag End');
        setIsDragging(false);
    }

    return (
        <div
            className={'draggable-popup'}    // position: absolute
            style={styles}
            onMouseDown={handleDragStart}
            onMouseMove={handleDragging}
            onMouseUp={handleDragEnd}
        >
            <div className={'draggable-popup-header'}>
                Header
            </div>
            <div className={'draggable-popup-body'}>
                This is the draggable popup body
            </div>
        </div>
    );
}

export default DraggablePopup;

with or without ‘return’ in javascript

I am solving a leetcode question. But I realized ‘return’ can make different output. The first code was accepted but the second one is not accepted.

function canJump(nums){
  let reachable = 0;
  
  for(let i=0; i < nums.length; i++){
    if(reachable < i) return false;
    reachable = Math.max(reachable, i + nums[i]);
  }
  return true;
function canJump(nums){
  let reachable = 0;
  
  for(let i=0; i < nums.length; i++){
    if(reachable < i) false;
    reachable = Math.max(reachable, i + nums[i]);
  }
  return true;

what is exactly the role of return in the javascript, and why does it make different output?

TS/JS/Node – Transparent Observation of a Pseudo 3rd Party Class

I have a base abstract class that I want public properties to be able to be Observed, including mutations if that property is an object/array/etc. This base class could take on a multitude of interfaces and other properties. I do not want someone who is using this base class to have to worry about events, a pub sub, or any other means of notification; I want that all just baked in.

abstract class BaseClass {
    #stores: Map<any, Function[]>

    subscribe(prop: NonFunctionPropertyNames<this>, callback: (data: CallbackType)=>void){
        // handle subscribe
    }

    unsubscribe(prop: NonFunctionPropertyNames<this>, callback: (data: CallbackType)=>void){
       // handle unsubscribe
    }

    constructor(){
        this.#stores = new Map<any, Function[]>
    }
}

I have attempted this using both Proxy and get/set each with their own pros and cons.

Proxy

  • Pros
    • Can intercept anything that happens on the proxied class including mutations
  • Cons
    • Does not copy private fields and any methods that reference a private field will error out the program

Get/Set

  • Pros
    • Does not need to clone methods and can therefore play nice with private fields
  • Cons
    • Only works on assignment and does not intercept any mutations that might happen on a property

I can live with the Get/Set approach, but that does mean anyone using this base class must be sure to re-assign a prop after any mutations. Is there some other approach I am missing?

JS clock project isnt running properly in that the hands wont move to follow the current time

I completed my JS clock project and the clock looks good however the clock hands wont follow the current time like it’s supposed to. Below I have my html code.

<!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">
    <link rel="stylesheet" href="style.css">
    <script defer src="script.js"></script>
    <title>JS Clock</title>
</head>
<body>
    <div class="clock">
        <div class="hand hour"></div>
        <div class="hand minute"></div>
        <div class="hand second"></div>
        <div class="number number1">1</div>
        <div class="number number2">2</div>
        <div class="number number3">3</div>
        <div class="number number4">4</div>
        <div class="number number5">5</div>
        <div class="number number6">9</div>
        <div class="number number7">7</div>
        <div class="number number8">8</div>
        <div class="number number9">9</div>
        <div class="number number10">10</div>
        <div class="number number11">11</div>
        <div class="number number12">12</div>
    </div> 
</body>
</html>


below is my JS code. Not sure if my code has a syntax error or my function is wrong.

setInterval(setClock, 1000)

const hourHand = document.querySelector('[data-hour-hand]')
const minuteHand = document.querySelector('[data-minute-hand]')
const secondHand = document.querySelector('[data-second-hand]')

function setClock() {
  const currentDate = new Date()
  const secondsRatio = currentDate.getSeconds() / 60
  const minutesRatio = (secondsRatio + currentDate.getMinutes()) / 60
  const hoursRatio = (minutesRatio + currentDate.getHours()) / 12
  setRotation(secondHand, secondsRatio)
  setRotation(minuteHand, minutesRatio)
  setRotation(hourHand, hoursRatio)
}

function setRotation(element, rotationRatio) {
  element.style.setProperty('--rotation', rotationRatio * 360)
}

setClock();

clock picture

Cannot read properties of undefined although my if statement also checks if it is undefined

I get TypeError: Cannot read properties of undefined (reading 'latestDocDate') with this:

if (this.state.latestDocDate === undefined || this.props.docRow[0].docDate > this.state.latestDocDate) {

There is a possibility this.state.latestDocDate could be undefined but I thought this.state.latestDocDate === undefined might cater for that. How do I resolve this?

textContent Value different in view than in DOM

Okay this is kinda peculiar problem that I’ve never had before. I’ll try to keep to quick and explain it as simply as possible. I have a page where a user can add and view some notes. Whenever someone clicks on a note, it opens a modal container to view the entire note. It finds the note using the closest method and then the content and the id of the note are passed to the modal container. Now whenever a user views a note (Say note A), the modal shows the content and id of note A. And if the user updates it (an update command is sent to firebase), the note does indeed gets updated. Works perfect. But if they now open note B, the modal container for some reason doesn’t show the content of note B. It shows the content of note A for some reason. The ID is still for note B. I checked the Element tab in the debugger and the DOM does indeed gets updated with the correct content and id in the modal container, however on the webpage view the content is still rendered from note A for some reason.

The attached image would explain better:

enter image description here

Here’s my code : It won’t run completely here because it requires a user logged into firebase but I just need help on the modal container part. This is just for reference. Thanks a ton in advance!

PS: If I refresh the page obviously modal container picks the right value because the list was probably updated or something.

<body>

    <div class="modal-container">
        <div id="background"></div>
        <div class="modal">
            <button class="modal__btn">&times;</button>
            <button class="modal__btn_b">Save</button>
            <!-- <h2 class="modal__title">Title bere</h2> -->
            <textarea id="modal__body">iis fugit possimus minus, repellendus dolores aliquid?</textarea>
            <textarea class="note__id">id should be here</textarea>
        </div>
    </div>




  

    <textarea id="todo-input" placeholder="Create a new todo..."></textarea>
    <button onclick="addItem(event)">Add</button>

    <div class="todo-items-wrapper">
        <div class="todo-items">
            <div class="todo-item">
                <div class="check">
                    <div class="check-mark checked">

                    </div>
                </div>
                <!-- <div class="todo-text checked">
                Cut the lawn
            </div> -->
            </div>
        </div>
    </div>

</body>

<script type="text/javascript">
    const todoitems = document.querySelector('.todo-items');
    const modalContainer = document.querySelector('.modal-container');



    function updateItem(notecontent, noteidd) {


        //   todoitems.innerHTML=""
       // event.preventDefault();

        //console.log(noteidd)

        let text = notecontent;
        let newItem = firebase.firestore().collection("users").doc(firebase.auth().currentUser.uid).collection('notes').doc(noteidd).update({

            content: text,
            createdAt: firebase.firestore.Timestamp.fromDate(new Date())

        })

    }

    function getItems() {

        var uid = null;

        firebase.auth().onAuthStateChanged(function (user) {
            if (user) {
                uid = user.uid;
                firebase.firestore().collection("users").doc(firebase.auth().currentUser.uid).collection('notes').orderBy("createdAt", "desc").onSnapshot((snapshot) => {
                    let items = [];

                    //   let itemsHTML = ""
                    let todoItems = []
                    snapshot.docs.forEach((doc) => {
                        items.push({
                            id: doc.id,
                            ...doc.data()
                        })
                    })
                    generateItems(items);
                })

            }
        })}

    function generateItems(items) {
       
        todoitems.innerHTML = ""

        items.forEach((item) => {
            const itemsHTML = document.createElement('div');
            itemsHTML.classList.add('item');
            itemsHTML.innerHTML = `
        <span class="span__id">${item.id}</span>
    
    <span class="note__body">${item.content}</span>
    
    <div class="note__btns">
      <button class="note__btn note__view">View Detail</button>
      <button class="note__btn note__delete">Delete Note</button>
    </div>
        `;

     todoitems.appendChild(itemsHTML)

        })

      
    }



    window.onload = getItems();





   
    todoitems.addEventListener('click', (e) => {

        if (e.target.classList.contains('note__view')) {
            const currentNote = e.target.closest('.item');
            const currentID = currentNote.querySelector('.span__id').textContent;
            const currentBody = currentNote.querySelector('.note__body').textContent;
           
            activateNoteModal(currentBody, currentID);
        }
    })




    function activateNoteModal(bodyy, noteid) {

        const modalBody = document.getElementById('modal__body');
        modalBody.textContent = bodyy;

        const note_id = document.querySelector('.note__id');
        note_id.textContent = noteid;

        modalContainer.classList.add('active');

 
    }



    const modalBtn = document.querySelector('.modal__btn').addEventListener('click', () => {
        modalContainer.classList.remove('active');
    })

    const modalSaveBtn = document.querySelector('.modal__btn_b').addEventListener('click', (e) => {
        
        e.preventDefault();

        const notecontent = document.getElementById('modal__body').value;
      
        const noteidd = document.querySelector('.note__id').value
        updateItem(notecontent, noteidd);
    })


</script>

How to map object into buttons in React Native?

I am trying to map out an array of objects into buttons on React Native, much like a calculator but I am having trouble doing so. Not sure if I am doing this right as it is breaking my app. I want the layout to be like this image hereenter image description here

export default function App() {

const Cards = [
{ card: "A", count: -1 },
{ card: "K", count: -1 },
{ card: "Q", count: -1 },
{ card: "J", count: -1 },
{ card: 10, count: -1 },
{ card: 9, count: 0 },
{ card: 8, count: 0 },
{ card: 7, count: 0 },
{ card: 6, count: 1 },
{ card: 5, count: 1 },
{ card: 4, count: 1 },
{ card: 3, count: 1 },
{ card: 2, count: 1 },
];

return (
 <View style={styles.container}>
  <View style={styles.CardPad}>
  {Cards.map((btn) =>
  
    <TouchableOpacity>
      {btn}
    </TouchableOpacity>
  
  )}
  </View>
  <Text>Open up App.js to start working on your app!</Text>
  <StatusBar style="auto" />
</View>
);
}

I’m sure the mapping feature on JS is meant to map out all the buttons to be laid out across a grid. I’ve done the styling for it but not sure if I should include it here or whether it is making a difference to the function itself. Or am I doing this entirely wrong?

Thanks

How to clear input fields and prevent submission?

Im having a form with several input fields and im trying to do a js script that while i click on a button my inputs become empty and my form does not submit.

This is my form:

let btnClear = document.querySelector('button');
            
            let inputs = document.querySelector('inputs');
            
            btnClear.addEventListener('click', () => {
                inputs.forEach(input => input.value = ' ');
                    
            });
      
      
 let $departemento = document.getElementById('departamento')
         let $provincia = document.getElementById('provincia')
         let $distrito = document.getElementById('distrito')

         let departamentos = ['Argentina', 'Brasil']
         let provincias = ['Bs As', 'Cordoba', 'San Pablo']
         let distritos = ['San Miguel', 'San Nicolas', 'Tigre', 'Belgrano', 'Calamuchita', 'La falda', 'Gral Belgrano', 'Santa Marta', 'Loa Loa']

         function mostrarLugares(arreglo, lugar) {
             let elementos = '<option selected disables>--Seleccione--</option>'

             for(let i = 0; i < arreglo.length; i++) {
                 elementos += '<option value="' + arreglo[i] +'">' + arreglo[i] +'</option>'
             }

             lugar.innerHTML = elementos
         }

         mostrarLugares(departamentos, $departemento)

         function recortar(array, inicio, fin, lugar) {
             let recortar = array.slice(inicio, fin)
             mostrarLugares(recortar, lugar)
         }

         $departemento.addEventListener('change', function() {
             let valor = $departemento.value

             switch(valor) {
                 case 'Argentina':
                     recortar(provincias, 0, 2, $provincia)
                 break
                 case 'Brasil':
                     recortar(provincias, 2, 3, $provincia)
                 break
             }

             $distrito.innerHTML = ''
         })

         $provincia.addEventListener('change', function() {
             let valor = $provincia.value

             if(valor == 'Bs As') {
                 recortar(distritos, 0, 4, $distrito)
             } else if(valor == 'Cordoba') {
                 recortar(distritos, 4, 7, $distrito)
             } else {
                 recortar(distritos, 7, 9, $distrito)
             }
         })
         
         
   <div class="container">
          <div class="row">
            <div class="col-12">
             <form  method="post" action="ServletPacientes">
              
                <h1 class="h1 mb-5" >Ingresar nuevo paciente</h1>
                <div class="form-row">
                <div class="form-group  col-md-4">
                  <div> 
                  <label>Nombre:</label> 
                  <input type="text" onkeypress="return checkLetras(event)" class="form-control" name="txtNombre" title="Ingrese su nombre" required /> </div>
                </div>
                <div class="form-group col-md-4">             
                  <div>
                  <label>Apellido:</label> 
                  <input type="text" onkeypress="return checkLetras(event)" class="form-control" name="txtApellido" required="">
                  </div>
                </div>
                
                <div class="form-group col-md-4">
                  <label>DNI: </label>
                  <input type="text" onkeypress="return check(event)" maxlength="8" minlength="7" class="form-control" name="txtDNI" required>
                </div>
                <div class="form-group col-md-4">
                  <label>Correo electrónico: </label>
                  <input type="email" class="form-control" name="txtCorreo" required>
                </div>
                
                
                
                <div class="form-group col-md-4">
                  <label>Teléfono: </label>
                  <input type="text" onkeypress="return check(event)" class="form-control" name="txtTelefono" required>
                </div>
                                                
                <div class="form-group col-md-4">
                  <label>Fecha de nacimiento: </label>
                  <input type="date" class="form-control " name="txtFechaNac" required>
                </div>
             
                
                 <div class="form-group col-md-4">
                        <label for="departamento" > Nacionalidad</label>
                        <select name="comboNacionalidad" id="departamento" class="form-control ">
                            <!-- cargaremos las etiquetas de option con javascript -->
                        </select>
                    </div>
      
                <div class="form-group col-md-4">
                    <label for="provincia"> Provincias</label>
                    <select name="comboProvincia" id="provincia" class="form-control ">
                        <!-- cargaremos las etiquetas de option con javascript -->
                    </select>
                </div>    
    
                    <div class="form-group col-md-4">
                        <label for="distrito" > Localidades</label>
                        <select name="comboLocalidad" id="distrito" class="form-control ">
                            <!-- cargaremos las etiquetas de option con javascript -->
                        </select>
                    </div>                             
                
                <div class="col-12">
                    <input onclick="confirmarAgregar(event)"  type="submit" class="btn btn-success" value="Aceptar" name="btnAceptar">
                    <button  type="" class="btn btn-outline-primary btnClear">Limpiar campos</button>
                </div>
               </div> 
              </form>
              
              
            </div>
          </div>
         </div>

For some reason my form is being submitted and redirecting me to another page and my texts are never emptying. I took the submit type to my but and still does not work.

Socket IO Generating multiple connections

Am using socket-io to do a delivery app, but i dont know why is generating me two connections, if only have a cellphone connected someone can help with that ?

I need to export the io to do emit and other thins in the routes petitions, type of when a new order is created, o a order is accepted.

Mi socketio.js code is this

import { Server as WebSocketServer } from "socket.io";
import http from "http";
import app from "../app";

const httpServer = http.createServer(app);
const io = new WebSocketServer(httpServer);

export {
  httpServer,
  io,
}

Mi index js is this.

import { httpServer, io } from "./middlewares/socketio";
import "./database";
require("dotenv").config();

var admin = require("firebase-admin");

var serviceAccount = require("./deliveram-test-firebase-adminsdk-vqinw-368ea4a624.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
});

io.on("connection", function (socket) {
  console.log("New Connection: ", socket.id);
});

httpServer.listen(process.env.PORT || 3000, () => {
  console.log("Server is running on port: " + process.env.PORT || 3000);
});

enter image description here

Response sends a null object even if object is not null

So what’s happening is I have a Handler that has 2 types of response, an object or an error. In the routes file, the error and the object arrive normally, but when it sends the response with the object to the client, it receives an empty object.

I tried changing res.reply to return result and checking if the result is not null before it was sent to client but it didn’t work.

src/Handlers/Professor.handler.js

const Professor = require('../Models/Professor.model');
const validator = require('validator');

/**
 * A Class for handling professor-related routes
*/
class ProfessorHandler {
  /**
   * Register a professor into system
   * @param {string} firstName
   * @param {string} lastName
   * @param {string} email
   * @param {string} password
   * @return {(object | Error)} Professor information
   *
*/
  async register({firstName, lastName, email, password}) {
    if (firstName.length === 0 ||
            lastName.length === 0 ||
            email.length === 0 ||
            password.length === 0) {
      return new Error('Missing fields');
    }

    if (validator.isEmail(email) === false) {
      return new Error('Invalid Email');
    };

    const emailAlreadyExists = await Professor.findOne({email});

    if (emailAlreadyExists) {
      return new Error('This email is already in use');
    };

    const professor = new Professor({firstName, lastName, email, password});

    await professor.save();
    await professor.generateToken();
    return {
      firstName: professor.firstName,
      lastName: professor.lastName,
      _id: professor._id,
      tokens: professor.tokens,
    };
  }
};

module.exports = ProfessorHandler;

src/Routes/Professor.route.js

        (...)
        fastify.post('/professor/register',
            registerProfessor,
            async (req, reply) => {
              const {firstName, lastName, email, password} = req.body;

              const service = new ProfessorHandler();
              const result = await service.register({
                firstName,
                lastName,
                email,
                password,
              });

              if (result instanceof Error) {
                return reply.code(400).send({
                  error: result.message,
                });
              };

              if (result === null) {
                return reply.code(400).send({
                  error: 'Object is null',
                });
              };

              return reply.send({professor: result});
            });

The object comes normally, but it arrives empty in the response. I added a console.log on result before reply.send

Image

How insert space before certain data?

I have next type of string

const string = 'some text some text in44 some text'

How I can transform it to next, with regexp / js code

const string = 'some text some text in 44 some text'

So, I just need insert space before every number value in string that comes after in.
Does it possible to implement?

Vue.js 2: return statement returning multiple values in parentheses

I have a Vue.js 2 app that I am now maintaining where there is a computed property. This computed property has a return statement that is returning several data properties in a comma-separated format, and the entire group is wrapped in parentheses.

I tried looking at both Javascript and Vue.js 2 documentation, and I can’t figure out what this is doing. In Javascript, if you wanted to return multiple values, you would return an array with the values or an object with multiple properties.

compoundFormProperty: function() {
  return (
    this.deliveryName,
    this.deliveryCity,
    this.deliveryAddress,
    this.deliveryState,
    this.deliveryCountry,
    this.deliveryPostal,
    Date.now()
  );
},