Like and save in paginated list

I am building a social media application on React.js. So on the homepage, I am showing a list of products. for those posts, features I want to achieve:-

  1. Let’s say X is a post and user Y like the post, so X contains a key called liked, initially liked: false. But when users like the post it should become true.
  2. When a user comes back to the application after some time, it should be liked: true by default for the current user.
  3. Similarly like Facebook, it behaves.

i tried to achieve it by comparing user like collection and post collection but that process it much expensive to. SO i need a optimised and fast way to achieve this feture.

Check if number is within a range

I have a total amount and then I have an amount that a user can insert.

I want to check whether the amount that the user insert is with 2 decimal places of the total amount.

eg. Total amount is 58.79 and the user inserts 58.78 or 58.80, if this is the case then I want to console out “Allowed” else if not the case then “Not allowed”.

another eg. Total amount is 60 and the user inserts 59.99 or 60.01, if this is the case then I want to console out “Allowed” else if not the case then “Not allowed”.

How can I go about this?

My attempt

  const Range = totalAmount - userInsertedAmount;
  if ( (Range < 0.2) || (Range > 0.2)) {
    console.log('valid');
  } else {
    console.log('invalid');
  }

One last thing, is there a way to do it without using any built in Javascript methods like abs etc.

How do I make it so that a value in a slider does not exceed a value from another slider?

I am implementing a chart using chartjs and I am using two sliders to configure the x-axis value range for the data that I am showing through html and javascript but I cannot figure out how to limit and/or stop the sliders once the sliders values reach the same number.

this is what I have currently for my sliders:

<div class = "slidercontainer">
    <div class = "range-slider">
        <span class="slider-track"></span>
        <input type="range" id="start" name="min-val" class="minvalue" min="1966" max="2022" value="1966" oninput="updateMin(this, 'end')">
        <input type="range" id="end" name="max-val" class="maxvalue" min="1966" max="2022" value="2022" oninput="updateMax(this, 'start')">
        <div class="slidernumformat">
            <ln>Years: </ln>
            <ln id="startYear">1966</ln>
            <ln> - </ln>
            <ln id="endYear">2022</ln>
        </div>
    </div>
</div>

I have tried to update the sliders by taking the id and putting it in the min or max values depending on which input I am trying to fix but it didn’t work.

Javascript:

const start = document.getElementById('start');
const end = document.getElementById('end');

start.max = 2022;
end.min = 1966;

function updateMin(range) {
    console.log(range.value);
    const minValue = labels.slice(parseInt(range.value) - 1966, parseInt(end.value) - 1965);
    const dbMinValue = datapoints.slice(parseInt(range.value) - 1966, parseInt(end.value) - 1965);
    myChart.config.data.labels = minValue;
    myChart.config.data.datasets[0].data = dbMinValue;
    end.min = parseInt(range.value);
    document.getElementById('startYear').textContent = range.value; // update the start year
    myChart.update();
}

function updateMax(range) {
    console.log(range.value);
    const maxValue = labels.slice(parseInt(start.value) - 1966, parseInt(range.value) - 1965);
    const dbMaxValue = datapoints.slice(parseInt(start.value) - 1966, parseInt(range.value) - 1965);
    myChart.config.data.labels = maxValue;
    myChart.config.data.datasets[0].data = dbMaxValue;
    start.max = parseInt(range.value);
    document.getElementById('endYear').textContent = range.value; // update the end year
    myChart.update();
}

function init() {
start.addEventListener('input', function(e) {
      start.value = e.target.value;
      updateMin(start);
                });
                end.addEventListener('input', function(e) {
                    end.value = e.target.value;
                    updateMax(end);
                });
            }

            init();

Is it possible to get the names or phone numbers of who texted me on iMessage using Swift or JavaScript?

I’m interested in making an iOS app that reminds me to respond every x hour whenever someone texts me. Is it possible to get that information, let’s say maybe through notifications from iMessage or directly from iMessage? I’m not looking to read the contents of the message since I know that is a privacy issue, but is it possible to retrieve who texted me and automatically sync that information with my app?

I have looked into retrieving iMessage information or notification information. It seems like iMessage contents cannot be accessed due to privacy restrictions but is it possible to just retrieve the name or phone number that texted me? It looks like it might be possible to get notification content so that can be a potential solution as well.

Thank you

trouble updating images in editing user profile

basically it is a social media app in which I’m trying to edit user profile pic and cover img by an input form and it is giving errors like not returning data after submitting the form, I’m using react.js,react-bootstrap for form, and react redux for state management, action reducers are giving me an error

so here are my files

// InfoCard.jsx (a card where basic information about user profile is displayed and a pen button to edit user profile)

import React, { useEffect, useState } from "react";
import "./InfoCard.css";
import ProfileModal from "../profileModal/ProfileModal";
import { useDispatch, useSelector } from "react-redux";
import { useParams } from "react-router-dom";
import * as UserApi from "../../api/UserRequest.js";
import { logOut } from "../../actions/AuthAction.js";



const InfoCard = () => {
  const dispatch = useDispatch();
  const params = useParams();
  const profileUserId = params.id;
  const [profileUser, setProfileUser] = useState({});
  const { user } = useSelector((state) => state.AuthReducer.authData);
  console.log("Authenticated user:", user);
  useEffect(() => {
    
    const fetchProfileUser = async () => {
      try {
        if (profileUserId === user._id) {
          setProfileUser(user);
          
        } else {
          const profileUser = await UserApi.getUser(profileUserId);
          setProfileUser(profileUser);
          console.log("Fetched profile user data:", profileUser);
        }
      } catch (error) {
        console.error("Error fetching profile user:", error);
      }
    };
    console.log(user);
    fetchProfileUser();
    console.log("profileUser in InfoCard.jsx : " + profileUser)
  }, [user]);

  const handleLogout = () => {
    dispatch(logOut());
    console.log("User logged out");
  };
  //console.log("InfoCard render - profileUser:", profileUser);


  return (
    <div className="InfoCard">
      <div className="infoHead">
        <h4>Profile Info</h4>
        {user._id === profileUserId ? (
          <div>
            
            <ProfileModal
          
              data = {user}
            />
          </div>
        ) : (
          ""
        )}
      </div>
      <div className="info">
        <span>
          <b>Status </b>
        </span>

        <span>{profileUser.relationship}</span>
      </div>
      <div className="info">
        <span>
          <b>Lives in </b>
        </span>
        <span>{profileUser.livesin}</span>
      </div>
      <div className="info">
        <span>
          <b>Works at </b>
        </span>
        <span>{profileUser.worksAt}</span>
      </div>
      <button className="button logout-button" onClick={handleLogout}>
        Logout
      </button>
    </div>
  );
};


export default InfoCard;

after clicking on to the pen button to edit profile modal is opened
// ProfileModal.jsx

import React, { useEffect } from "react";
import Button from "react-bootstrap/Button";
import Modal from "react-bootstrap/Modal";
import { useState } from "react";
import { UilPen } from "@iconscout/react-unicons";
import Form from "react-bootstrap/Form";
import { useDispatch } from "react-redux";
import { useParams } from "react-router-dom";
import { UploadImage } from "../../actions/UploadAction.js";
import { UpdateUser } from "../../actions/UserAction.js";


function ProfileModal( {data} ) {
  const [show, setShow] = useState(false);
  const handleClose = () => setShow(false);
  const handleShow = () => setShow(true);
  const { password, ...other } = data
  const dispatch = useDispatch()
  const params = useParams()
  
 // maybe its because we have made the data a state whhich is stupid as how can we change state 
 const [formData, setFormData] = useState(other);
  const [profileImage, setProfileImage]  = useState("")
  const [coverImage, setCoverImage] = useState("")
  //const { user } = useSelector((state) => state.AuthReducer.authData);
//console.log(data);
  const handleChange = (e) => {
    setFormData({...formData, [e.target.name]: e.target.value})
  }
const onImageChange = (e) => {
  if (e.target.files && e.target.files[0]) {
    let img = e.target.files[0];
    console.log("Selected image:", img);
    if (e.target.name === "profileImage") {
      setProfileImage(img);
      console.log("Profile image set:", img);
    } else if (e.target.name === "coverImage") {
      setCoverImage(img);
      console.log("Cover image set:", img);
    }
  }
};

  // form submission
  const handleSubmit = async (e) => {
    e.preventDefault();
    let UserData = formData;
    
    if (profileImage) {
      const data = new FormData();
      const fileName = Date.now() + profileImage.name;
      data.append("name", fileName);
      data.append("file", profileImage);
      UserData.profilePicture = fileName;
      try {
        dispatch(UploadImage(data));
      } catch (err) {
        console.log("profileimg error" + err);
      }
      if (coverImage) {
        const data = new FormData();
        const fileName = Date.now() + coverImage.name;
        data.append("name", fileName);
        data.append("file", coverImage);
        UserData.coverPicture = fileName;
        try {
          dispatch(UploadImage(data));
        } catch (err) {
          console.log("coverImg error" +err);
        }
      }
      dispatch(UpdateUser(params.id, UserData));
    }

  };
  
  


  return (
    <>
      <UilPen
        width="2rem"
        height="1.2rem"
        variant="primary"
        onClick={handleShow}
      />
      <Modal
        dialogClassName="modal-dialog modal-xl modal"
        size="xxl"
        aria-labelledby="contained-modal-title-vcenter "
        centered
        show={show}
        onHide={handleClose}
      >
        <Modal.Header closeButton>
          <Modal.Title>Your Info</Modal.Title>
        </Modal.Header>
        <Modal.Body
          style={{ maxHeight: "70vh", overflowY: "auto" }}
          className="modal-body"
        >
          <Form>
            <Form.Group className="mb-3" controlId="exampleForm.ControlInput1">
              <Form.Label>First Name</Form.Label>
              <Form.Control
                type="text"
                placeholder="Enter your first name"
                className="border-0 bg-input p-3"
                name="firstname"
                onChange={handleChange}
                value={formData.firstname}
                style={{
                  backgroundColor: "var(--inputColor)",
                  outline: "none",
                  boxShadow: "none",
                  padding: "10px 15px", // Adjust the padding as needed
                }}
              />
            </Form.Group>

            <Form.Group className="mb-3" controlId="exampleForm.ControlInput2">
              <Form.Label>Last Name</Form.Label>
              <Form.Control
                type="text"
                placeholder="Enter your last name"
                className="border-0 bg-input p-3"
                name="lastname"
                onChange={handleChange}
                value={formData.lastname}
                style={{
                  backgroundColor: "var(--inputColor)",
                  outline: "none",
                  boxShadow: "none",
                  padding: "10px 15px", // Adjust the padding as needed
                }}
              />
            </Form.Group>

            <Form.Group className="mb-3" controlId="exampleForm.ControlInput3">
              <Form.Label>Works at</Form.Label>
              <Form.Control
                type="text"
                placeholder="Enter your workplace"
                className="border-0 bg-input p-3"
                name="worksAt"
                onChange={handleChange}
                value={formData.worksAt}
                style={{
                  backgroundColor: "var(--inputColor)",
                  outline: "none",
                  boxShadow: "none",
                  padding: "10px 15px", // Adjust the padding as needed
                }}
              />
            </Form.Group>

            <Form.Group className="mb-3" controlId="exampleForm.ControlInput4">
              <Form.Label>Lives In</Form.Label>
              <Form.Control
                type="text"
                placeholder="Enter your location"
                className="border-0 bg-input p-3"
                name="livesin"
                onChange={handleChange}
                value={formData.livesin}
                style={{
                  backgroundColor: "var(--inputColor)",
                  outline: "none",
                  boxShadow: "none",
                  padding: "10px 15px", // Adjust the padding as needed
                }}
              />
            </Form.Group>

            <Form.Group className="mb-3" controlId="exampleForm.ControlInput5">
              <Form.Label>Country</Form.Label>
              <Form.Control
                type="text"
                placeholder="Enter your country"
                className="border-0 bg-input p-3"
                name="country"
                onChange={handleChange}
                value={formData.country}
                style={{
                  backgroundColor: "var(--inputColor)",
                  outline: "none",
                  boxShadow: "none",
                  padding: "10px 15px", // Adjust the padding as needed
                }}
              />
            </Form.Group>

            <Form.Group className="mb-3" controlId="exampleForm.ControlInput6">
              <Form.Label>Relationship Status</Form.Label>
              <Form.Control
                type="text"
                placeholder="Enter your relationship status"
                className="border-0 bg-input p-3"
                name="relationship"
                onChange={handleChange}
                value={formData.relationship}
                style={{
                  backgroundColor: "var(--inputColor)",
                  outline: "none",
                  boxShadow: "none",
                  padding: "10px 15px", // Adjust the padding as needed
                }}
              />
            </Form.Group>

            <Form.Group
              className="mb-3"
              controlId="exampleForm.ControlTextarea1"
            >
              <Form.Label>About</Form.Label>
              <Form.Control
                className="border-0 bg-input p-3"
                as="textarea"
                placeholder="Tell us about yourself"
                rows={3}
                name="about"
                onChange={handleChange}
                value={formData.about}
                style={{
                  backgroundColor: "var(--inputColor)",
                  outline: "none",
                  boxShadow: "none",
                  padding: "10px 15px", // Adjust the padding as needed
                }}
              />
            </Form.Group>

            <Form.Group className="mb-3" controlId="exampleForm.ControlInput7">
              <Form.Label>Profile Image</Form.Label>
              <Form.Control
                type="file"
                name="profileImage"
                onChange={onImageChange}
                
                style={{
                  outline: "none",
                  boxShadow: "none",
                  padding: "10px 15px", // Adjust the padding as needed
                }}
              />
            </Form.Group>

            <Form.Group className="mb-3" controlId="exampleForm.ControlInput8">
              <Form.Label>Cover Image</Form.Label>
              <Form.Control
                type="file"
                name="coverImage"
                onChange={onImageChange}
                style={{
                  outline: "none",
                  boxShadow: "none",
                  padding: "10px 15px", // Adjust the padding as needed
                }}
              />
            </Form.Group>
          </Form>
        </Modal.Body>

        <Modal.Footer>
          <button className="button info-btn " onClick={handleSubmit}>Update</button>
        </Modal.Footer>
      </Modal>
    </>
  );
}


export default ProfileModal;

now in the modal all fields are updated correctly except images field, images changes are being held correctly as the data is being console logged displaying the changes, bu i think that on submitting there is an error while dealing with profile Img and cover img, and append is being underlined in red by vs code itself, UploadImage is returning null data, although upload image is successfully uploading posts in the app so it is clear maybe that the backend is fine

// possible error

    if (profileImage) {
      const data = new FormData();
      const fileName = Date.now() + profileImage.name;
      data.append("name", fileName);
      data.append("file", profileImage);
      UserData.profilePicture = fileName;
      try {
        dispatch(UploadImage(data));
      } catch (err) {
        console.log("profileimg error" + err);
      }
      if (coverImage) {
        const data = new FormData();
        const fileName = Date.now() + coverImage.name;
        data.append("name", fileName);
        data.append("file", coverImage);
        UserData.coverPicture = fileName;
        try {
          dispatch(UploadImage(data));
        } catch (err) {
          console.log("coverImg error" +err);
        }
      }

since Im using React redux so heres my redux structure

//UploadRequest.js

import axios from "axios";

const API = axios.create({ baseURL: "http://localhost:5000" });

API.interceptors.request.use((req) => {
  if (localStorage.getItem('profile')) {
    req.headers.Authorization = `Bearer ${JSON.parse(localStorage.getItem('profile')).accessToken}`;
  }
  return req;
});

export const UploadImage = (data) => API.post("/upload/", data);
export const UploadPost = (data) => API.post("/posts", data);

images are being stored and being posted correctly in the app so the backend seems fine

// UploadAction.js

import * as UploadApi from "../api/UploadRequest";


export const UploadImage = (data) => async (dispatch) => {
  try {
    console.log("Image upload Action start ho gya hy")
    console.log("UploadImage data:" + data) // here it is returning UploadImage data:[object FormData]
    await UploadApi.UploadImage(data);
  } catch (error) {
    
    console.log(error);
    dispatch({ type: "UPLOAD_FAIL" });
   
  }
};

export const UploadPost = (data) => async (dispatch) => {
  dispatch({ type: 'UPLOAD_START' });
  try {
    const newPost = await UploadApi.UploadPost(data);
    dispatch({ type: 'UPLOAD_SUCCESS', data: newPost });
  } catch (error) {
    console.log(error);
    dispatch({ type: 'UPLOAD_FAIL' });
  }
};

so on the frontend it seems like everything is updated correctly but when i close and reopen the modal the image fields are emptied again and the profile and over img are being shown as error

// PostReducer.js
this is where uploading state are being managed

const PostReducer = (
  state = { posts: [], loading: false, error: false, uploading: false },
  action
) => {
  switch (action.type) {
    // belongs to PostShare.jsx
    case "UPLOAD_START":
      return { ...state, error: false, uploading: true };
    case "UPLOAD_SUCCESS":
      return {
        ...state,
        posts: [action.data, ...state.posts],
        uploading: false,
        error: false,
      };
    case "UPLOAD_FAIL":
      return { ...state, uploading: false, error: true };
}
}
export default PostReducer;

z-index not working on element with smoothscrolling , gSAP

I am not able to show the fixed button when scrolling over images, i tried different things but nothing seems to work even if i z-index:999999999999999;

Image uses smooth scrolling with gsap, now sure what should be change or if z-index property doesnt work with transform: translate(-50%, -50%)..... property which changes for image wrapper when scrolling

const select = e => document.querySelector(e);
const selectAll = e => document.querySelectorAll(e);

const panels = selectAll(".panel")

function startAnim() {
  
  panels.forEach((panel, i) => {
    let imageWrappers = panel.querySelectorAll(".col__image-wrap")
    console.log(imageWrappers)
    
    gsap.fromTo(imageWrappers, {
      y: "-30vh"
    }, {
      y: "30vh",
      scrollTrigger: {
        trigger: panel,
        scrub: true,
        start: "top bottom", // position of trigger meets the scroller position
      },
      ease: 'none'
    })
  })
}

function init() {
  startAnim();
}

window.onload = () => init()



const lenis = new Lenis()

lenis.on('scroll', (e) => {
  console.log(e)
})

function raf(time) {
  lenis.raf(time)
  requestAnimationFrame(raf)
}

requestAnimationFrame(raf)
.enquire-btn{ background-color: #222; color: #fff; min-width:150px; 
  padding:10px 25px; border-radius: 100px; text-decoration: none; 
  font-weight: normal; font-size: 14px;
  position: -webkit-sticky;
  position: sticky;
  position:fixed;
  z-index:99999999999999999999; 
}
body{background:#fff;}
.header{hight:60px; min-height:60px; background:#fff; ;
}
.h-line{height:1px; background:#000; margin-top:15px; }
.hero-section{margin-top:200px; z-index:20;}
.hs {
  text-transform: uppercase;
  font-family:Overusedgrotesk,sans-serif;
  color:#222;
  font-weight:200;
 letter-spacing: -5px;
font-size: clamp(2.1875rem, 0.9037rem + 5.4054vw, 9.6875rem);
}
.hs:first-child {font-weight:600; padding-right:10px;}


*, .panel, .project {
  padding: 0;
  margin: 0;
}

/* Full width section */
.panel {
  display: flex;
  justify-content: center;
  align-items: stretch;
  height: 90vh;
  overflow: hidden;
  margin-top: 0vh;
  margin-bottom:0vh;
/*     background-color: red; */
}

/* In charge of setting the height/width/area */
.column {
  flex-basis:100%;
  position: relative;
  overflow: hidden;
}

/* Extra height for the parallax effect */
.col__image-wrap {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 100%;
    height: 160vh;
    background-color: red;
}

/* make sure it covers the total space */
.img {
    object-fit: cover;
    width: 100%;
    height: 100%;
}

.intro-section{min-height:300px; background:grey; padding:30px 0px;}
.intro-section .section-heading {
  position:relative; withd:100%; padding:30px; 
  color:#fff; font-size:18px;}
<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/5.3.3/cerulean/bootstrap.min.css" rel="stylesheet"/>

<header class="container-fluid text-center header animate__animated animate__fadeIn animate__delay-800ms">
  <div class="row justify-content-evenly vertical-align p-3 ">
    <div class="col-4 align-middle">AHRE</div>
    <div class="col-4 ms-auto">      <a class="enquire-btn animate__animated animate__fadeInUp animate__slower">CONTACT US</a></div>
</div>
    <div class="h-line animate__animated animate__slideInLeft animate__delay-900ms"></div>
  </div>
</header>
<section class="container-fluid hero-section">
  <span class="hs animate__animated animate__fadeInUp animate__delay-1s">The Residences</span>
</section>
<section class="container-fluid section2 p-0">
   <div class="panel panel--1">
    <div class="column">
      <div class="col__image-wrap">
      <img class="img img--1" src="https://assets-global.website-files.com/6594c68e852eed392813f26c/65968d19211871302df255cc_home-img-07.webp" />
    </div>
    </div>
  </div>
 
 
</section>
<section class="intro-section">
  <div> <span class="section-heading">Introduction</span></div>
</section>

<script src="https://unpkg.com/[email protected]/dist/lenis.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.5.1/ScrollTrigger.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.5.1/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/js/bootstrap.min.js"></script>

Dynamically added SVG animation sometimes not firing

<!DOCTYPE html>
<html>
    <head>
        <style>
            #test {
                background-color: lightgray;
                height: 300px;
                width: 300px;
            }
            .ball {
                fill: black;
                r: 10px;
            }
        </style>
    </head>
    <body>
        <svg id="test" />
        <script>
            function anim() {
                const circ = document.createElementNS("http://www.w3.org/2000/svg", "circle");
                circ.setAttribute("class", "ball");
                circ.setAttribute("cx", 0);
                circ.setAttribute("cy", 0);
                const anim = document.createElementNS("http://www.w3.org/2000/svg", "animateTransform");
                anim.setAttribute("attributeName", "transform");
                anim.setAttribute("type", "translate");
                anim.setAttribute("begin", "indefinite");
                anim.setAttribute("from", "0,0"); 
                anim.setAttribute("to", "300,300");
                anim.setAttribute("dur", "2s");
                anim.setAttribute("repeatCount", "1");
                anim.addEventListener("endEvent", (e) => {e.target.parentElement.remove();});
                circ.append(anim);
                test.append(circ);
                anim.beginElement();
            }
            const test = document.querySelector("#test");
            test.addEventListener("mouseenter", anim);
        </script>
    </body>
</html>

In this example, a ball (SVG circle) is created each time the mouse hovers over the gray square. An animation from the top left to top right is added to the ball and then triggered.

Sometimes, at least in the latest version of Chrome, the ball is created but the animation does not render until the next event trigger. Where am I going wrong?

Having trouble updating information in my MongoDB Atlas Database using NextJS

I’m working on a mock admin panel for a mock storefront using NextJS, Tailwind, MongoDB Atlas, and Mongoose. I’ve put together a document that holds my ‘GET’ code, ‘POST’ code, ‘PUT’ code, and ‘DELETE’ code. So far the GET, POST, and DELETE commands work; however, I’m unable to get the PUT command to work.
This is code from a previous project that I put together from a video series I found on YouTube…and it worked fine in that project

First, the document that holds my commands…

import { mongooseConnect } from "@/lib/mongoose";
import { Product } from "@/models/Product";
import { ObjectId } from "mongodb";

export default async function handle(req, res) {
    // This will store the required properties
    const { method } = req;
    // This will connect to the database
    await mongooseConnect();

    

    // This will grab product(s) from the database
    if (method === 'GET') {
        if (req.query?.id) {
            res.json(await Product.findOne({ _id: req.query.id }));
        } else {
            res.json(await Product.find());
        }
        //res.json(await Product.find());
    }

    // This will create a new product in the database
    if (method === 'POST') {
        const { title, description, price } = req.body;
        const productDoc = await Product.create({
            title, description, price
        })
        res.json(productDoc);
    }

    // This will update a product in the database
    if (method === 'PUT') {
        const {title,description,price,_id} = req.body;
        var id = new ObjectId(_id);
        console.log(id);
        await Product.updateOne({id}, {title,description,price});
        res.json(true);
    }

    // This will delete a product from the database
    if (method === 'DELETE') {
        if (req.query?.id) {
            await Product.deleteOne({ _id: req.query?.id });
            res.json(true);
        }
    }
}

The code that I utilized in the other project, for the PUT command, looked like this…

    if (method === 'PUT') {
        const {title,description,price,_id} = req.body;
        await Product.updateOne({id}, {title,description,price});
        res.json(true);
    }

This didn’t work in this project and after some searching I found that ‘_id’ was trying to be used as a string; so, I changed the code a bit to make it an ObjectId…

Here is the document that handles the item…in this case a product…

import axios from "axios";
import Link from "next/link";
import { useRouter } from "next/router";
import { useState } from "react";

export default function ProductForm({
    _id,
    title: existingTitle,
    description: existingDescription,
    price: existingPrice,
}) {

    // States
    const [title, setTitle] = useState(existingTitle || "");
    const [description, setDescription] = useState(existingDescription || "");
    const [price, setPrice] = useState(existingPrice || "");
    const [goToProducts, setGoToProducts] = useState(false);

    const router = useRouter();

    // Save product to the database
    async function saveProduct(ev) {
        ev.preventDefault();
        const data = {
            title,
            description,
            price,
        };
        if (_id) {
            try {
                // update
                await axios.put("/api/products/", [{ ...data, _id }]);
            } catch (error) {
                console.log(error);
            }
        } else {
            // create
            await axios.post('/api/products', data);
        }
        // redirect back to product page
        setGoToProducts(true);
    }


    if (goToProducts) {
        router.push('/products');
    }

    return (
        <form onSubmit={saveProduct}>
            {/* Product Name */}
            <label>Product Name</label>
            <input
                type="text"
                placeholder="Product Name"
                value={title}
                onChange={(ev) => setTitle(ev.target.value)}
            />

            {/* Product Category */}
            {/* <label>Category</label> */}


            {/* Product Description */}
            <label>Product Description</label>
            <textarea
                type="text"
                placeholder="Description"
                value={description}
                onChange={(ev) => setDescription(ev.target.value)}
            ></textarea>

            {/* Product Price */}
            <label>Price</label>
            <input
                type="number"
                placeholder="Price"
                value={price}
                onChange={(ev) => setPrice(ev.target.value)}
            />

            <div>
                <button type="submit" className="btn-primary mr-5">
                    Save
                </button>
                <Link href={'/products'} type="button" className="btn-red text-xl tracking-wide">
                    Cancel
                </Link>
            </div>

        </form>
    )
}

And here is the code snippet that actually activates the different commands…

 // Save product to the database
    async function saveProduct(ev) {
        ev.preventDefault();
        const data = {
            title,
            description,
            price,
        };
        if (_id) {
            try {
                // update
                await axios.put("/api/products/", [{ ...data, _id }]);
            } catch (error) {
                console.log(error);
            }
        } else {
            // create
            await axios.post('/api/products', data);
        }
        // redirect back to product page
        setGoToProducts(true);
    }

As mentioned above I can get the POST, GET, and DELETE commands to work just fine.

I’ve tried converting the _id from a string to an ObjectId. Which was supposed to make MongoDB recognize it as an ID; however, this doesn’t seem to be the case as the product I’m trying to update is not updated.
I’ve added a console.log for _id in my api as follows…

    // This will update a product in the database
    if (method === 'PUT') {
        const {title,description,price,_id} = req.body;
        **console.log(req.body._id);**
        var id = new ObjectId(_id);
        **console.log(id);**
        await Product.updateOne({id}, {title,description,price});
        res.json(true);
    }

…and I get the following output…
undefined,
new ObjectId(‘6673add4380496a134b753ea’)

Can someone please help me figure this out…I haven’t found anything online for this specific issue.
Also, if I’m missing anything, please let me know

Is there a way to prevent echo json_encode() return the JSON response with the whole page when submitting form to the same PHP script?

I’ve got this only index.php file in the project. I know I should separate the logic from the view, use different files for PHP, JS and HTML. This is only a test:

<?php
    if($_SERVER["REQUEST_METHOD"] == "POST") {        
        if(isset($_POST["item"]) && $_POST["item"] == "new") {
            $description = filter_input(INPUT_POST, trim("description"));
            echo json_encode($description);
        }        
    }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Itens</title>
</head>
<body>
    <form method="post">
        <input type="text" name="description" placeholder="Description">
        <button type="submit">Add Item</button>
    </form>

    <script>
        const form = document.querySelector("form")
        form.addEventListener('submit', async (e) => {
            e.preventDefault()
            const item = "new"
            const description = form.description.value            
            const formData = new FormData()
            formData.append("item", item)
            formData.append("description", description)            
            try {
                await fetch('./index.php', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'Accept': 'application/json, text/plain, */*'                
                    }
                })
                .then((res) => res.json())
                .then((data) => {                    
                    alert(data)                    
                })
            } 
            catch(error) {}
        })
    </script>
    
</body>
</html>

The echo json_encode() works and sends the response, but also sends the whole page, reloading the index.php, which makes impossible work with the response value in the JavaScript fetch code. When working with echo json_encode() in a different script from code who called it, that doesn’t happen, of course. Is it possible to fix this keeping this one file structure?

How can i adding Google-Translate to my web page?

I want to add google translate for my website which supports all countries of the world. so that I can make it look the way I want (editable and customizable) (html, css, js)

I don’t know where to start, I tried so many ways, but none of them were customizable or I didn’t know how.

web app google script can not access html element with javascript function

I have a simple html file with labels and text fields with ids (like firstname id=“fn”, lastname id=“ln”, and address id=“add”). So far my web app runs fine with inline Javascript that gets the value of these elements and stores them in a google sheet. So far “nothing” I try will let me getElementById with the google script. It’s the “exact” same code but one runs inline with the html file and the other one run in an html file in the web app as google script.

I have tried every way possible to getElementById in my google script and it I always get the same answer which is “TypeError: Cannot read properties of undefined (reading ‘firstName’)”. This is the simple code:
var userInfo = {};
userInfo.firstName = document.getElementById(“fn”).value;

This code is to be executed when the user types in his name and address and then clicks the button when done.

Is there a way to support ESM and node/NPM without an import map?

I’m working on a library that I publish as ESM. A primary goal is to allow it to be used without a build step, or even without using node/npm at all (just clone the repo and import). But I also realize most devs will want to use npm and consume the library that way.

It wouldn’t be a problem to support both workflows, except that my library depends on d3js. If I want ESM to work, I have to either vendor d3, or import it directly through URLs with a CDN. But this breaks NPM’s dependency resolution, ie if someone used my library and also used d3js directly, their app would include 2 separate copies of d3, even if it was the exact same version.

The best workaround I’ve found so far is to import d3 with a bare specifier (ie import * as d3 from 'd3') and use an import map with ESM to override it to import from jsdelivr (example below). This works, but I would love to ditch the import map. Is this possible?

Here’s an example (codepen):

<script type=importmap>
  {
    "imports": {
      "d3": "https://cdn.jsdelivr.net/npm/d3@7/+esm"
    }
  }
</script>

<script type='module' src="https://cdn.jsdelivr.net/npm/[email protected]/index.js"></script>

<iobio-data-broker
  url="https://s3.amazonaws.com/iobio/NA12878/NA12878.autsome.bam">
</iobio-data-broker>

<iobio-histogram
  broker-key="coverage_hist">
</iobio-histogram>