Cannot avoid null values in HTML

I am using a combination of Javascript and HTML to achieve the generation of a PDF inside NetSuite.

I have a loop that I need to ignore the null values but it is not working. The table has 10 column and the idea is to iterate over column2 to ignore null values of the entire table.

The <tr> at the bottom is what I will be printing in the table.

How can I make so that my results exclude the rows for the null values column2 has?

for (let i = 0; i < recordObjs.length; i++) { 
                        if (recordObjs.column2[i] == null) {
                            i++; }
                            

                   htm += `
                    
                        <tr>
                            <td>${recordObjs[i].column0}</td>
                            <td>${recordObjs[i].column2}</td>
                            <td>${numberWithCommas(parseFloat(recordObjs[i].column3), '$')}</td>
                            <td >${recordObjs[i].column4}</td>
                        </tr>`;

                   }

Blogger manual adsense placement using javascript

I have a blogger website with automatic placement, but I think that’s ruined my article. I want to make a custom adsense placement by replacing the text that want to the ads. For example, I want the text “showadshere” to be the ads. I’ve searched about Javascript DOM but haven’t had any success.

I expect that I can replace specific text in the article with ads.

POST 404 (not found) with typescript frontend to python (flask) backend

Trying to send a formData instance from frontend to backend, and then receive a response.

This is the code in the frontend

// Make the fetch call
    fetch('/upload-file', {
      method: 'POST',
      body: formData
    })
    .then(response => response.json())
    .then(data => {
      console.log('Received score:', data.score);
    })
    .catch(error => {
      console.error('Error:', error);
    });

And this is the route I have made in the back-end:

@app.route('/upload-file', methods=['POST'])
def upload_file():
    uploaded_file = request.files['Blob']
    
    # if file is present
    if uploaded_file.filename != '':
        # save the file
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], uploaded_file.filename)
        uploaded_file.save(file_path)

        # placeholder score
        import random
        score = random.randint(0, 100)

        return jsonify({'score': score})

    return jsonify({'error': 'No file uploaded'}), 400

The error message I get is POST http://localhost:5173/upload-file 404 (Not Found)

I’ve tried changing the route names in both spaces… not sure if it’s because the route is triggered in a subpage? I did try to make it the route /subpage/upload-file but that didn’t seem to work either.

Thanks

why this code stopped rendering the DOM element without refresh to the frontend

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
</head>

<body>
    <div id="addStudentModal" class="modal fade">
        <div class="modal-dialog">
            <div class="modal-content">
                <form id="addStudentForm">
                    @csrf
                    <div class="modal-header">
                        <h4 class="modal-title">Add New User</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label>User Name</label>
                            <input type="text" class="form-control" name="name" required>
                        </div>
                        <div class="form-group">
                            <label>Email</label>
                            <input type="Email" class="form-control" name="email" required>
                        </div>
                        <div class="form-group">
                            <label>Password</label>
                            <input type="password" class="form-control" name="password" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
                        <input type="submit" class="btn btn-success" value="Add">
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script>
        $(document).ready(function() {
            $('#addStudentForm').submit(function(event) {
                event.preventDefault();

                var formData = new FormData(this);

                $.ajax({
                    url: '/store',
                    type: 'POST',
                    data: formData,
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        if (response.success) {
                            $('#addStudentModal').modal('hide');
                            $('#studentTable').append('<tr><td>' + response.user.name +
                                '</td><td>' + response.user.email + '</td></tr>');
                        } else {
                            alert('Error: ' + response.message);
                        }
                    }
                });
            });
        });
    </script>
</body>

</html>

the code above was behaving normally and was immediately appending the HTML code, and displaying it on the screen without any need to reload the screen, may you tell me why now I have to refresh the screen for this code to display the new HTML element on the screen?

the change in behavior maybe happened after I created another modals in another views, but I have no idea how that could affect the behavior of the current one, I also created new functions in the admincontroller!

I am getting an error on Count function – eslint: no-return assign – Return statement should not contain assignment. How do I resolve this?

basically my script creates a hyperlink based on a webpage information. When a user clicks that hyperlink, it will send them to an image page. Now, I wanted to have a count of clicks on that hyperlink and display the total counts (incrementing) to another page. What I have tried is below code where it suppose to count the clicks but I am getting an error:

eslint: no-return assign – Return statement should not contain
assignment.

Also, if someone can help me resolve this, is it also possible to display that counts in another page? And if I refresh that page, the counts will not reset?

I will post part of the script for your review. Thank you very much in advance. Have a great day!

//This will create that link into a page
let link = document.createElement("a");
            var linkText = document.createTextNode(images2[j].name);               
            link.appendChild(linkText);
            link.title = images2[j].name;
            link.href = images2[j].image_src;
            link.target = '_blank';
            document.querySelector('[class^="testui_tabs-content"]').prepend(link);

let eventListenerFunction = (e) => {log('A link was clicked'); }
            document.querySelectorAll('[class^="testui_tabs-content"]').forEach(linkText => {
            link.addEventListener("click", eventListenerFunction );
});


//This will log user clicks to a Slack Channel

function log(msg){

const ticketurl = window.location.href;
const url = 'https://hooks.slack.com/workflows/Test';
const headers = {'Content-Type': 'application/x-www-form-urlencoded'};

let data = `${msg}, ${ticketurl}, ${new Date().toISOString()}, v${GM_info.script.version}`;

data = {'Content': data};
request('POST', url, '', headers, data);


//Counts the click on the hyperlink with error
var count = (function () {        
var counter = 0;
return function () {return counter +=1;}
    
})();

function displaycount(){
document.getElementById("log").innerHTML = count();

Custom Angular modal service does not work correctly, component does not receive updates

I’m creating a service in Angular to open the components inside my modal, but I noticed something… for some reason, after I inject the content of my component inside the modal and insert it into the html of my page, things inside my component do not work as they should.

For example, when I am normally on my route to the component that I want to open via modal, it works correctly, I enter the data in the form, it checks whether it is valid or invalid and releases the save button… But, when this same component is opened by my modal service, it simply remains immutable, even after completing all the fields, it still remains invalid, it’s as if it didn’t change anything, remaining in an immutable state.

My code:

import { Injectable, Injector, ComponentFactoryResolver, Type, Inject } from "@angular/core";
import { Observable, Subject } from "rxjs";
import { ModalComponent } from "../components/modal/modal.component";
import { DOCUMENT } from "@angular/common";

@Injectable({
    providedIn: 'root'
})
export class ModalService {

    private modalNotifier!: Subject<void>;

    constructor(private resolver: ComponentFactoryResolver, private injector: Injector, @Inject(DOCUMENT) private document: Document) {}
    
    open(component: Type<any>, options: { title?: string, width?: string, height?: string }): Observable<any> {

        // Cria o componente de modal.
        const modalComponentFactory = this.resolver.resolveComponentFactory(ModalComponent);
        const modalDynamicComponent = modalComponentFactory.create(this.injector);
        
        // Configura as variáveis internas do modal.
        modalDynamicComponent.instance.closeEvent.subscribe(() => this.close());
        modalDynamicComponent.instance.title = options?.title;
        modalDynamicComponent.instance.width = options?.width;
        modalDynamicComponent.instance.height = options?.height;

        // Detecta as mudanças nas váriaveis do instance.
        modalDynamicComponent.changeDetectorRef.detectChanges();

        // Cria o component especifico.
        const componentFactory = this.resolver.resolveComponentFactory(component);
        const componentRef = componentFactory.create(this.injector);

        componentRef.changeDetectorRef.detectChanges();

        // Adiciona o conteudo do componente criado no modal.
        modalDynamicComponent.instance.contentViewRef.insert(componentRef.hostView);

        // Adiciona na página o modal.
        this.document.body.appendChild(modalDynamicComponent.location.nativeElement);

        this.modalNotifier = new Subject();
        return this.modalNotifier.asObservable();

    }

    close() {
        this.modalNotifier.next();
        this.modalNotifier.complete();
    }

}

Dynamic TailwindCSS custom styles not applied in Next.js components

Description:

I’m building a Next.js app with TailwindCSS where I retrieve player data from Riot Games APIs. Using a player’s “tier” data (e.g., ‘EMERALD’), I aim to dynamically set a container’s background color. However, certain dynamic Tailwind styles aren’t being applied.

The data is retrieved like this

ladder rank:  [
  {
    leagueId: '<id>',
    queueType: 'RANKED_SOLO_5x5',
    tier: 'EMERALD',
    rank: 'IV',
    summonerId: '<summonerId>',
    summonerName: '<playerName>',
    leaguePoints: 0,
    wins: 65,
    losses: 61,
    veteran: false,
    inactive: false,
    freshBlood: true,
    hotStreak: false
  }
]

The frontend div container classname is like this

className={`w-48 h-64 border-4 ${data ? getRankStyles(data.tier) : ''} ...`}

The getRankStyles is a util function I created that looks like this

type Tier = 
  | 'IRON'
  | 'BRONZE'
  | 'SILVER'
  | 'GOLD'
  | 'PLATINUM'
  | 'EMERALD'
  | 'DIAMOND'
  | 'MASTER'
  | 'GRANDMASTER'
  | 'CHALLENGER';


export const getRankStyles = (rank: string) => {

    console.log("Ranked passed: ", rank)
    // switch (rank) {
    //     case 'IRON':
    return `border-${rank} bg-${rank} bg-opacity-25`;
    //     case 'BRONZE':
    //         return 'border-tier-bronze bg-tier-bronze bg-opacity-25';
    //     case 'SILVER':
    //         return 'border-tier-silver bg-tier-silver bg-opacity-25';
    //     case 'GOLD':
    //         return 'border-tier-gold bg-tier-gold bg-opacity-25';
    //     case 'PLATINUM':
    //         return 'border-tier-platinum bg-tier-platinum bg-opacity-25';
    //     case 'EMERALD':
    //         return 'border-tier-emerald bg-tier-emerald bg-opacity-25';
    //     case 'DIAMOND':
    //         return 'border-tier-diamond bg-tier-diamond bg-opacity-25';
    //     case 'MASTER':
    //         return 'border-tier-master bg-tier-master bg-opacity-25';
    //     case 'GRANDMASTER':
    //         return 'border-tier-grandmaster bg-tier-grandmaster bg-opacity-25';
    //     case 'CHALLENGER':
    //         return 'border-tier-challenger bg-tier-challenger bg-opacity-25';
    //     default:
    //         return 'border-gray-400 bg-gray-400';
    // }
}

I included the commented out code to show other ways I’ve tried to solve this issue.

Tailwind Configuration:

In tailwind.config.js, I’ve added custom colors under theme.extend.colors and other related properties. For example:

Issues Observed:

-Custom styles from tailwind.config.js don’t seem to apply dynamically to the className according to the player’s tier.
-Fixed styles work fine.

Steps Tried:

  1. I’ve verified that there are no errors in the browser developer tools. The elements tab show the class being applied. But the Styles tab does not show the styles. There doesn’t seem to be any overlapping styles either.
  2. Checked postcss.config.js for correct plugins.
  3. Played around with the content array in tailwind.config.js and tried disabling purging.
  4. Ensured proper TailwindCSS integration with Next.js.

Any insights or suggestions would be appreciated.

This is my tailwind.config file

import type { Config } from 'tailwindcss'

const config: Config = {
  content: [
    './pages/**/*.{js,ts,jsx,tsx,mdx}',
    './components/**/*.{js,ts,jsx,tsx,mdx}',
    './app/**/*.{js,ts,jsx,tsx,mdx}',
  ],
  theme: {
    extend: {
      colors: {
        'riot-dark': '#2D2D2D',
        riot: {
          primaryRed: '#d13639',
          secondaryRed: '#F12B15',
          black: '#000000',
          grayBlack: '#2D2D2D',
          white: '#FFFFFF'
        },
        lol: {
          primaryBlue: '#0bc6e3',
          lighterBlue: '#CDFAFA',
          darkerBlue: '#0A1428',
          functionalityGold: '#e0b667',
          lolbutton: '#0AC8B9',
          lolbuttonHover: '#0A323C',
          buttonText: '#0A323C',
          buttonTextHover: '#0AC8B9',
        },
        borderColor: {
          IRON: '#43464B',
          BRONZE: '#8B4513',
          SILVER: '#C0C0C0',
          GOLD: '#FFD700',
          PLATINUM: '#E5E4E2',
          EMERALD: '#50C878',
          DIAMOND: '#1E90FF',
          MASTER: '#9932CC',
          GRANDMASTER: '#4169E1',
          CHALLENGER: '#00008B', 
        },
        backgroundColor: {
          'riot-card': '#5B5A56',
          'riot-red': '#ff4248',
          'riot-gray1': '#A09B8C',
          'riot-gray1.5': '#5B5A56',
          'riot-gray2': '#3C3C41',
          'riot-gray3': '#1E2328',
          IRON: '#43464B',
          BRONZE: '#8B4513',
          SILVER: '#C0C0C0',
          GOLD: '#FFD700',
          PLATINUM: '#E5E4E2',
          EMERALD: '#50C878',
          DIAMOND: '#1E90FF',
          MASTER: '#9932CC',
          GRANDMASTER: '#4169E1',
          CHALLENGER: '#00008B',
        },
        backgroundImage: {
          'gradient-radial': 'radial-gradient(var(--tw-gradient-stops))',
          'gradient-conic':
            'conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))',
      }
      },
    },
  },
  plugins: [],
}
export default config;

as a beginner I need explainations about sharing or hosting my website

So, I’m a junior devlopper, still studying. I never actually had a real project yet.
In my studies, I learn about web-dev and started digging in it. I got really interested and started making more complex websites.
But always local hosted.

Recently, I had an econter with someone that really needed a website for something. It was quite complex since it was an online 2 player game + a host acting as a spectator. I never done something like this before. But I managed to do it. I’m using react for my framework, with Tailwind for the css. And the project is split between server and client side

But here’s where the issue starts. Now that I have finished the project, that everything works as expected on my side, that I’m able to connect with different browsers and play the game on my computer. How do I give him the files?

This is not really accurate, as a developper In a real scenario, how are you usualy supposed to return the project? Do you just dump all the folders to your client and he’s supposed to know what to do with it? I’m not sure mine have enough knowledge for that.

But even myself, I wouldn’t know how to host my onw website like this. I know react have a build feature, but I never used it. I’m also confused about my server side, is it also supposed to be hosted in the same place as the website? and do I just replace the “localhost:3003” by the actual URL of the website?
In both cases, I have to run “npm run dev” for my client side to start, and “npm start” for my server to start. How will my host provider know this? Is it something you’re supposed to do?

I’m including you the server sided code so you see what I mean:

import express from "express";
import cors from "cors";
import { StreamChat } from "stream-chat";
import { v4 as uuidv4 } from "uuid";
import bcrypt from "bcrypt";
import axios from "axios"; 
const app = express();

app.use(cors());
app.use(express.json());
const api_key = "hf4a7sb9mwzp"; 
const api_secret =
  "thisISnotTheRealApiKeyForObviousReasons";
const serverClient = StreamChat.getInstance(api_key, api_secret);

app.post("/signup", async (req, res) => {
  try {
    const { clash_id, username, password } = req.body;
    const userId = uuidv4();
    const hashedPassword = await bcrypt.hash(password, 10);
    const token = serverClient.createToken(userId);
    res.json({ token, userId, clash_id, username, hashedPassword });
  } catch (error) {
    res.json(error);
  }
});

app.post("/login", async (req, res) => {
  try {
    const { username, password } = req.body;
    const { users } = await serverClient.queryUsers({ name: username });
    if (users.length === 0) return res.json({ message: "User not found" });

    const token = serverClient.createToken(users[0].id);
    const passwordMatch = await bcrypt.compare(
      password,
      users[0].hashedPassword
    );

    if (passwordMatch) {
      res.json({
        token,
        clash_id: users[0].clash_id,
        username,
        userId: users[0].id,
      });
    }
  } catch (error) {
    res.json(error);
  }
});

app.post("/joinchannel", async (req, res) => {
  try {
    const { gameID, UserID, token } = req.body;
    const channelType = "messaging";
    
    const AuthToken = token;
     // Replace with your authentication token

    const apiUrl = `https://chat.stream-io-api.com/channels/${channelType}/${gameID}?api_key=${api_key}`;

    // Make a POST request to add members to the channel using Axios
    const response = await axios.post(
      apiUrl,
      {
        add_members: [UserID],
      },
      {
        headers: {
          Accept: "application/json",
          "Stream-Auth-Type": "jwt",
          Authorization: AuthToken, // Replace with your JWT token
          "Content-Type": "application/json",
        },
      }
    );

    // Check if the response is successful and return the data
    if (response.status === 200) {
      res.json(response.data);
    } else {
      // Handle errors if needed
      res.status(response.status).json({ message: "Error adding user to channel" });
    }
  } catch (error) {
    console.log(error);
    res.status(500).json({ message: "Internal Server Error" });
  }
});

app.listen(3001, () => {
  console.log("Server is running on port 3001");
});

here’s a component that makes a call to the server:

function Login({ setIsAuth }) {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");

  const cookies = new Cookies();
  const login = () => {
    Axios.post("http://localhost:3001/login", { /*Am I supposed to tell him "just replace this by the url of the website"?*/
      username,
      password
    }).then((res) => {
      console.log(res);
      if(res.data.token)
      {
        const {token, clash_id,  username, userId } = res.data;
        cookies.set("token", token);
        cookies.set("userId", userId);
        cookies.set("username", username);
        cookies.set("clash-ID", clash_id)
        setIsAuth(true);
      }
      else
      {
        setError(true);
      }
      }
      
    
    );
  };
  let error_message 
  if (error) error_message = <><h3 className=" text-sm text-red-600">User/password doesn't match, try again</h3></>;
  else error_message = <></>
  return (
    <div className="flex flex-col w-96 h-80 border rounded-lg bg-white text-center content-center ">
      <label className=" font-bold text-2xl text-center"> Login</label>

      <input className=" w-80 h-12 p-4 m-4 text-xl bg-transparent border-b-2 border-black self-center"
        placeholder="Username"
        onChange={(event) => {
          setUsername(event.target.value);
        }}
      />
      <input className="w-80 h-12 p-4 m-4 text-xl bg-transparent border-b-2 border-black self-center"
        placeholder="Password"
        type="password"
        onChange={(event) => {
          setPassword(event.target.value);
        }}
      />
      {error_message}
      <button className="w-48 h-12 border rounded-md hover:bg-slate-400 self-center translate-y-10 font-bold" onClick={login}> Login</button>
      
    </div>
    
  );
}

export default Login;

Damn, this is confusing… I’m sure for you professionals this will sound like a silly question, but it’s a question I’m not the only one asking. It’s not that evident when you never done it before. Tbh, I really have no idea on how I’m suppose to share the final project with my client.
I’m not sure my explainations for the issue were acurate enough for you to understand my problem. But I hope that one of you can give me the informations I need!

Thank you for your help,
Have a nice day 🙂

UploadThing error TypeError: Cannot read properties of undefined (reading ‘url’) Nextjs 13.4.12

I’m trying to upload an image using UploadThing, but every time I get a 500 error saying that the url is undefined as shown below. Here are my relevant api routes and components I also get this using the network tab’s request payload: {“files”:[“testimage.jpg”]}

"use client";

import toast from "react-hot-toast";

import { UploadDropzone } from "@/lib/uploadthing";
import { ourFileRouter } from "@/app/api/uploadthing/core";

interface FileUploadProps {
  onChange: (url?: string) => void;
  endpoint: keyof typeof ourFileRouter;
}

export const FileUpload = ({ onChange, endpoint }: FileUploadProps) => {
  return (
    <UploadDropzone
      endpoint={endpoint}
      onClientUploadComplete={(res) => {
        onChange(res?.[0].url);
      }}
      onUploadError={(error) => {
        console.log(error);
        toast.error(`${error?.message}`);
      }}
    />
  );
};

import { createNextRouteHandler } from "uploadthing/next";

import { ourFileRouter } from "./core";

// Export routes for Next App Router
export const { GET, POST } = createNextRouteHandler({
  router: ourFileRouter,
});

import { auth } from "@clerk/nextjs";
import { createUploadthing, type FileRouter } from "uploadthing/next";

import { isTeacher } from "@/lib/teacher";

const f = createUploadthing();

const handleAuth = () => {
  const { userId } = auth();
  const isAuthorized = isTeacher(userId);

  if (!userId || !isAuthorized) throw new Error("Unauthorized");
  return { userId };
};

export const ourFileRouter = {
  courseImage: f({ image: { maxFileSize: "4MB", maxFileCount: 1 } })
    .middleware(() => handleAuth())
    .onUploadComplete(() => {}),
  courseAttachment: f(["text", "image", "video", "audio", "pdf"])
    .middleware(() => handleAuth())
    .onUploadComplete(() => {}),
  chapterVideo: f({ video: { maxFileCount: 1, maxFileSize: "512GB" } })
    .middleware(() => handleAuth())
    .onUploadComplete(() => {}),
} satisfies FileRouter;

export type OurFileRouter = typeof ourFileRouter;

"use client";

import * as z from "zod";
import axios from "axios";
import { Pencil, PlusCircle, ImageIcon, File, Loader2, X } from "lucide-react";
import { useState } from "react";
import toast from "react-hot-toast";
import { useRouter } from "next/navigation";
import { Attachment, Course } from "@prisma/client";
import Image from "next/image";

import { Button } from "@/components/ui/button";
import { FileUpload } from "@/components/file-upload";

interface AttachmentFormProps {
  initialData: Course & { attachments: Attachment[] };
  courseId: string;
}

const formSchema = z.object({
  url: z.string().min(1),
});

export const AttachmentForm = ({
  initialData,
  courseId,
}: AttachmentFormProps) => {
  const [isEditing, setIsEditing] = useState(false);
  const [deletingId, setDeletingId] = useState<string | null>(null);

  const toggleEdit = () => setIsEditing((current) => !current);

  const router = useRouter();

  const onSubmit = async (values: z.infer<typeof formSchema>) => {
    try {
      await axios.post(`/api/courses/${courseId}/attachments`, values);
      toast.success("Course updated");
      toggleEdit();
      router.refresh();
    } catch {
      toast.error("Something went wrong");
    }
  };

  const onDelete = async (id: string) => {
    try {
      setDeletingId(id);
      await axios.delete(`/api/courses/${courseId}/attachments/${id}`);
      toast.success("Attachment deleted");
      router.refresh();
    } catch {
      toast.error("Something went wrong");
    } finally {
      setDeletingId(null);
    }
  };

  return (
    <div className="mt-6 border bg-slate-100 rounded-md p-4">
      <div className="font-medium flex items-center justify-between">
        Course attachments
        <Button onClick={toggleEdit} variant="ghost">
          {isEditing && <>Cancel</>}
          {!isEditing && (
            <>
              <PlusCircle className="h-4 w-4 mr-2" />
              Add a file
            </>
          )}
        </Button>
      </div>
      {!isEditing && (
        <>
          {initialData.attachments.length === 0 && (
            <p className="text-sm mt-2 text-slate-500 italic">
              No attachments yet
            </p>
          )}
          {initialData.attachments.length > 0 && (
            <div className="space-y-2">
              {initialData.attachments.map((attachment) => (
                <div
                  key={attachment.id}
                  className="flex items-center p-3 w-full bg-sky-100 border-sky-200 border text-sky-700 rounded-md"
                >
                  <File className="h-4 w-4 mr-2 flex-shrink-0" />
                  <p className="text-xs line-clamp-1">{attachment.name}</p>
                  {deletingId === attachment.id && (
                    <div>
                      <Loader2 className="h-4 w-4 animate-spin" />
                    </div>
                  )}
                  {deletingId !== attachment.id && (
                    <button
                      onClick={() => onDelete(attachment.id)}
                      className="ml-auto hover:opacity-75 transition"
                    >
                      <X className="h-4 w-4" />
                    </button>
                  )}
                </div>
              ))}
            </div>
          )}
        </>
      )}
      {isEditing && (
        <div>
          <FileUpload
            endpoint="courseAttachment"
            onChange={(url) => {
              if (url) {
                onSubmit({ url: url });
              }
            }}
          />
          <div className="text-xs text-muted-foreground mt-4">
            Add anything your students might need to complete the course.
          </div>
        </div>
      )}
    </div>
  );
};

Here is the following output when trying to upload an image file using the FileUpload component from the attachment-form:

[UT] UploadThing dev server is now running!
- error TypeError: Cannot read properties of undefined (reading 'url')
   at eval (webpack-internal:///(rsc)/./node_modules/uploadthing/dist/chunk-LQBAB5WK.mjs:257:36)
   at Object.POST (webpack-internal:///(rsc)/./node_modules/uploadthing/dist/chunk-66XXRAVC.mjs:285:32)
   at POST (webpack-internal:///(rsc)/./node_modules/uploadthing/dist/next.mjs:19:31)
   at eval (webpack-internal:///(rsc)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:253:43)
   at eval (webpack-internal:///(rsc)/./node_modules/next/dist/server/lib/trace/tracer.js:111:36)
   at NoopContextManager.with (webpack-internal:///(rsc)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:360:30)
   at ContextAPI.with (webpack-internal:///(rsc)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:30:58)
   at NoopTracer.startActiveSpan (webpack-internal:///(rsc)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:953:34)
   at ProxyTracer.startActiveSpan (webpack-internal:///(rsc)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:993:36)
   at eval (webpack-internal:///(rsc)/./node_modules/next/dist/server/lib/trace/tracer.js:100:107)
   at NoopContextManager.with (webpack-internal:///(rsc)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:360:30)
   at ContextAPI.with (webpack-internal:///(rsc)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:30:58)
   at NextTracerImpl.trace (webpack-internal:///(rsc)/./node_modules/next/dist/server/lib/trace/tracer.js:100:32)
   at eval (webpack-internal:///(rsc)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:241:53)
   at AsyncLocalStorage.run (node:async_hooks:330:14)
   at Object.wrap (webpack-internal:///(rsc)/./node_modules/next/dist/server/async-storage/static-generation-async-storage-wrapper.js:42:24)
   at eval (webpack-internal:///(rsc)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:195:97)
   at AsyncLocalStorage.run (node:async_hooks:330:14)
   at Object.wrap (webpack-internal:///(rsc)/./node_modules/next/dist/server/async-storage/request-async-storage-wrapper.js:77:24)
   at eval (webpack-internal:///(rsc)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:194:75)
   at AsyncLocalStorage.run (node:async_hooks:330:14)
   at AppRouteRouteModule.execute (webpack-internal:///(rsc)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:191:56)
   at AppRouteRouteModule.handle (webpack-internal:///(rsc)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:314:41)
   at RouteHandlerManager.handle (/home/ssmith/Development/code/capstone/e-learning-api/lms-client/node_modules/next/dist/server/future/route-handler-managers/route-handler-manager.js:24:29)
   at runMicrotasks (<anonymous>)
   at processTicksAndRejections (node:internal/process/task_queues:96:5)
   at async doRender (/home/ssmith/Development/code/capstone/e-learning-api/lms-client/node_modules/next/dist/server/base-server.js:1009:38)
   at async cacheEntry.responseCache.get.incrementalCache.incrementalCache (/home/ssmith/Development/code/capstone/e-learning-api/lms-client/node_modules/next/dist/server/base-server.js:1218:28)
   at async /home/ssmith/Development/code/capstone/e-learning-api/lms-client/node_modules/next/dist/server/response-cache/index.js:99:36

put two cards side by side with tailwind

I am doing a practice project to learn new technologies like tailwind which is the first time I use it, I want it to be side by side without overlapping.

example of how it is currently being over-used

enter image description here

How can I do it?

<body>
  <div id="app">
    <h1 class="text-4xl text-center">Task</h1>
    
    <div class="grid grid-cols-12 p-4">
      <div class="col-span-9 m-4">
        <span>
                    <input
                            type="text"
                            placeholder="Escribe una tarea"
                            class="input input-bordered w-full"
                            v-model="task"
                            @keyup.enter="addTask"
                            id="task_input" />
                    </span>
      </div>
      
      <div class="col-span-3 m-4">
        <button class="btn btn-primary" @click="addTask" id="task_button">
          Agregar
        </button>
      </div>

      <div class="grid grid-cols-3 gap-4" id="cardContainer">
        <div class="card min-w-0 max-w-md">
          <div class="card w-96 bg-base-100 shadow-xl" id="task_card">
            <div class="card-body">
              <h2 class="card-title">Card title!</h2>
              
              <p id="task_text" class="text-base-content">
                If a dog chews shoes whose shoes does he choose?
              </p>
              
              <div class="card-actions justify-end">
                <button class="btn btn-primary">Buy Now</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script src="https://cdn.tailwindcss.com"></script>
  <!-- <script type="module" src="/main.js"></script> -->
</body>

Cannot read properties of undefined (reading ‘pathname’) in React

I have set my routes in the App.js file. but I got an error when I change the url of my project. I created an state component called movieState.js where I have 3 objects with different url´s.

So anytime I write ‘http://localhost:3000/work/bicycle’ I got the following error – Cannot read properties of undefined (reading ‘pathname’)

This is my App.js:

//Styles
import "./styles/app.scss";

//Global Style from styled-components
import GlobalStyle from "./components/GlobalStyle";

//Router
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

//import Pages
import AboutUs from './pages/AboutUs';
import OurWork from './pages/OurWork';
import ContactUs from './pages/ContactUs';
import MovieDetail from "./pages/MovieDetail";

//Nav component
import Nav from './components/Nav';




function App() {
  return (
    <div className="App">
      <GlobalStyle />
      <Nav />
      <Routes>
        <Route path="/" element={<AboutUs />} />
        <Route path="/work" element={<OurWork />} />
        <Route path="/work/:id" element={<MovieDetail />} />
        <Route path="/contact" element={<ContactUs />} />
      </Routes>
    </div>
  );
}

export default App;

This is my movieState.js where I have all my data;


//Import Images
import { color } from "framer-motion";
import bicycle from "./img/bycicle.jpg";
import colorwall from "./img/colorwall.jpg";
import light from "./img/light.jpg";

export const MovieState = () => {
  return [
    {
      title: "The Bicycle",
      mainImg: bicycle,
      secondaryImg: bicycle,
      url: "/work/bicycle",
      awards: [
        {
          title: "Truly A masterpiece",
          description:
            "“Lorem Ipsum is simply dummy text of the printing and typesetting industry.”",
        },
        {
          title: "Fresh look on a brutal sport.",
          description:
            "“Lorem Ipsum is simply dummy text of the printing and typesetting industry.”",
        },
        {
          title: "It’s okay lmao.",
          description:
            "“Lorem Ipsum is simply dummy text of the printing and typesetting industry.”",
        },
      ],
    },
    {
      title: "The Color Wall",
      mainImg: colorwall,
      url: "/work/colorwall",
      secondaryImg: colorwall,
      awards: [
        {
          title: "Truly A masterpiece",
          description:
            "“Lorem Ipsum is simply dummy text of the printing and typesetting industry.”",
        },
        {
          title: "Fresh look on a brutal sport.",
          description:
            "“Lorem Ipsum is simply dummy text of the printing and typesetting industry.”",
        },
        {
          title: "It’s okay lmao.",
          description:
            "“Lorem Ipsum is simply dummy text of the printing and typesetting industry.”",
        },
      ],
    },
    {
      title: "The Light",
      mainImg: light,
      url: "/work/light",
      secondaryImg: light,
      awards: [
        {
          title: "Truly A masterpiece",
          description:
            "“Lorem Ipsum is simply dummy text of the printing and typesetting industry.”",
        },
        {
          title: "Fresh look on a brutal sport.",
          description:
            "“Lorem Ipsum is simply dummy text of the printing and typesetting industry.”",
        },
        {
          title: "It’s okay lmao.",
          description:
            "“Lorem Ipsum is simply dummy text of the printing and typesetting industry.”",
        },
      ],
    },
  ];
};

This is my nav.js:


import React from 'react';
import styled from 'styled-components';
import { Link } from 'react-router-dom';

function Nav() {

  return (
    <StyledNav>
        <Link to="/">
            <h1>Logo</h1>
        </Link>
        
        <ul>
            <li><Link to="/" className='li'>About Us</Link></li>
            <li><Link to="/work" className='li'>Our Work</Link></li>
            <li><Link to="/contact" className='li'>Contact Us</Link></li>
   
        </ul>

    </StyledNav>
  )
}

Moviedetail.js

import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { MovieState } from '../movieState';

function MovieDetail() {

  const navigate = useNavigate();
  const url = navigate.location.pathname;
  const [movies,setMovies] = useState(MovieState); 
  const [movie,setMovie] = useState(null);

  //useEffect runs after the component is mounted
  useEffect(() => {
    const currentMovie = movies.filter((stateMovie) => stateMovie.url === url);
    setMovie(currentMovie);
  }, [movies,url]);

  return (
    <div>
        <h1>Movie Detail</h1>
    </div>
  )
}

export default MovieDetail;

enter image description here

require is not defined in electron.js app

I am having an issue when attempting to import a library using the require method. I get an error that goes Uncaught ReferenceError: require is not defined. I have got nodeIntegration set to true in the main.js file and I am trying to use a library (I get the same error for any library) by using:

window.socket = require('websocketio');

inside if renderer.js.

I have tried using the contextBridge.exposeInMainWorld method in a preload.js file and having the file referenced in main.js when I create the new window.

const isDev = process.env.NODE_ENV !== 'production';
let mainWindow;

// Creates the main window
function createMainWindow() {
    mainWindow = new BrowserWindow({
    width: isDev ? 1920 : 1280,
    height: 720,
    icon: './images/icon.ico',
    webPreferences: {
        contextIsolation: true,
        nodeIntegration: true,
        preload: path.join(__dirname, 'preload.js'),
    }
});

// Opens the dev tools if in development mode
if (isDev) {
    mainWindow.webContents.openDevTools();
}

mainWindow.loadFile(path.join(__dirname, './renderer/index.html')).then(r => console.log(r));
//mainWindow.loadURL('http://127.0.0.1');

}

Migrate Tamper Monkey Script to standalone extensions

I am trying to migrate some tamper monkey script into a standalone chrome extension; however, I am running into a few errors with some functions.

const InputEvents = {};
    function pressKey(key) {
        const wordsInput = document.getElementById("wordsInput");
        const KeyboardEvent = Object.assign({}, DEFAULT_INPUT_OPTIONS, { target: wordsInput, data: key });
        const InputEvent = Object.assign({}, DEFAULT_KEY_OPTIONS, { target: wordsInput, key: key });

        wordsInput.value += key;
        InputEvents.beforeinput(InputEvent);
        InputEvents.input(InputEvent);
        InputEvents.keyup(KeyboardEvent);
    }

function hook(element) {
        element.addEventListener = new Proxy(element.addEventListener, {
            apply(target, _this, args) {
                const [type, listener, ...options] = args;
                if (_this.id === "wordsInput") {
                    InputEvents[type] = listener;
                }
                return target.apply(_this, args);
            }
        })
    }
    hook(HTMLInputElement.prototype);

I say this because this code, from a different author, works in TamperMonkey userscript, but when I put the same script into my script.js file or in a browser’s console, it throws an error saying .beforeinput() or .input() or .keyup() is not a function. I tried messing around with Google’s bard which suggested some changes with polyfills, which I am unsure of. I not as well versed in Javascript and chrome extensions as I’m new to this area. Any help is much appreciated.

How do I make a transparent wix widget not block content behind it?

Im making a plugin for wix and am using the “Wix Blocks” editor, The widget has a fixed position on the screen in the bottom right. The problem is that if there is some site content behind the widget it is blocked / non interactable, so i made the widget resizable via a min / max button but it still blocks the background elements even when there seems to be nothing there.

Ive tried using wix/velo api’s collapse() function on the root widget element. I was expecting it would collapse it completely but there still seems to be an invisible i frame there.

Wix’s api really limits javascript functionalities, if i were able to access DOM i could easily resize the iframe itself but i can’t and im not that experienced with Wix / Velo. There also are very few resources on wix plugin development.

How to fade out flash message

I’ve been stuck for hours trying to figure out how to get the flash message to fade out once the user is logged in.
I find find any documentation that for setting a time for req.flash

app.get("/signin", function(req, res){
   req.flash("success", 'Successfully logged in.')
   fadeOut(function() {
    req.flash("success", 'Successfully logged in.').fadeOut();
  }, 3000)

;

I’ve tried setTimout and another and other similar functions