Getting the error: “Component not defined”

import React from 'react';
class Navbar extends React.Component {
  
  render() {
    return (
      <nav className="navbar navbar-expand-lg bg-body-tertiary">
        <div className="container-fluid">
          <a className="navbar-brand" href="#">
            Navbar
          </a>

//code continues.....

The error being displayed:

ERROR in [eslint]
srcComponentsnavbar.js
  Line 2:22:  'Component' is not defined  no-undef

I have also tried the other way around by writing the code like this:

import React, {Component} from 'react';
class Navbar extends Component {

But somehow the error is not being resolved.

PWA Timer in Background

I am trying to build a Pomodoro-style timer into my SvelteKit PWA, so that it can run in the background when the app is closed (or unfocussed) and send the user a push notification when it has finished. However, I am not quite sure how to achieve this, while also having it work offline. I have done a bit of reasearch and found that the Background Sync API would not work for this.

How would I go about making this work? Is it possible in a PWA? And if not, is there another way to try to implement this (preferably using one codebase)?

Show on the frontend results returned from a server action in Next JS

I’m new to NEXT JS and I wanted to test it because of the new Server actions function.

I have created a form that, on Submit, launches a server action that fetches some data from an API.

page.tsx

import Form from "@/components/Form";

export default function Home() {
  return (
    <div className="container mx-auto flex justify-center items-center h-screen">
      <Form />
    </div>
  );
}

form.tsx

"use client";

import { requestImg } from "@/actions/formActions";

export const Form = () => {
  return (
    <form
      className="bg-white p-8 rounded shadow-md"
      action={async (formData) => {
        await requestImg(formData);
      }}
    >
    ... other stuff ...
   </form>
  );
};

export default Form;

formActions.ts

"use server";

export const requestImg = async (FormData: FormData) => {
  const link = FormData.get("link");

  const response = await fetch(
    `https://<my API link>/get-all-images/`,
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        link_post: link,
      }),
    }
  );
  const result = await response.json();
  console.log(result);
};

My question is, now, how do I show the result (it is an array of image links) on the front end? Are there some “best practices”?

My idea was to get the ID of the div element I want to update with new HTML and do something like

const results = document.getElementById('result');
results.innerHTML += `
    <img src="results[0]">
`

but, I don’t think it is the best practice, especially with NEXT JS

Blender + Three.js animation

so I got myself a 3d model of a umbrella which already comes with a animation which opens and closes it. Now i imported it into my project using Three.js and played the animation.

Using the code I found out that its actualy two animations, yet both of them are not what I expected, one just rotates the umbrella and the other just moves the pusher up and down, but doesnt take the top and its supporting sticks with it. (like its displayed in blender). I guess it has something to do with the way those things are connected in blender, sadly I have no experience with blender, so I ask you guys.

so this is my code:

import * as React from 'react';
import { Canvas, useFrame } from '@react-three/fiber';
import { Suspense, useState, useRef, useEffect } from 'react';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { OrbitControls, useGLTF } from '@react-three/drei';
import * as THREE from 'three';

const Model = ({ playAnimation }) => {
const gltf = useGLTF(require("../svg/Part3.glb"));
const mixer = useRef();

// Increase the scale to make the model larger
gltf.scene.scale.set(200, 200, 200);

// Set up animation mixer
if (!mixer.current) {
    mixer.current = new THREE.AnimationMixer(gltf.scene);
    gltf.animations.forEach((animation) => {
        const action = mixer.current.clipAction(animation);
        action.play();
    });
    console.log(gltf.animations)
}

// Update the animation mixer on each frame
useFrame((state, delta) => mixer.current.update(delta));

// Play animation when playAnimation is true
useEffect(() => {
    if (playAnimation) {
        mixer.current.timeScale = 1;
    } else {
        mixer.current.timeScale = 0;
    }
}, [playAnimation]);

return <primitive object={gltf.scene} />;
};

const Umbrella = () => {
const [playAnimation, setPlayAnimation] = useState(false);

const handleButtonClick = () => {
    setPlayAnimation(!playAnimation);
};

return (
    <div>
    <Canvas camera={{ position: [0, 0, 1000], fov: 75, near: 1, far: 5000 }} style={{  backgroundColor:       

    "black", position: "relative", width: "100%", height: "90vh" }}>
            <directionalLight position={[2000, 2000, 2000]} intensity={1} color="white" />
            <pointLight position={[10, 10, 10]} intensity={0.6} />
            <Suspense fallback={null}>
                <Model playAnimation={playAnimation} />
            </Suspense>
            <OrbitControls />
        </Canvas>
        <button onClick={handleButtonClick}>{playAnimation ? 'Pause Animation' : 'Play Animation'}  

  </button>
    </div>
);
};

export default Umbrella;

altough I am pretty sure it has nothing to do with the code.

And this is how it should look like:
Beginning of the animation

middle of animation
(after this it jsut opens again)

I would like to provide you the file but I didnt see an option to do so and I payed a few € for this file, so I am not even sure if it would be legal..

Anyways, maybe somebodys has tipps or usefull imformation.
`

Using cache-control: only-if-cached

I would like to make a request from browser JS code that only succeeds if there is a response in the cache, and otherwise errors.

The Cache-Control: only-if-cached header discussed here on MDN sounds like just what I need:

The client indicates that an already-cached response should be returned. If a cache has a stored response, even a stale one, it will be returned. If no cached response is available, a 504 Gateway Timeout response will be returned.

But in practice I just can’t get that to work. If I run this code in the console on any page on the web:

fetch("/" + Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(), {
  headers: {
    "Cache-Control": "only-if-cached",
  },
}).then((res) => {
  console.log('Fetch', res.status);
});

I just get a plain old 404 and I can see that an HTTP request was made to the server. Why doesn’t this result in a 504? I observe the same behavior in both Chrome and Firefox.

I also found a top-level option in the fetch API that sounds like it’s supposed to do the same thing. As discussed on MDN here fetch supports a cache property in its request options, which also supports only-if-cached as a value. It states there:

only-if-cached — The browser looks for a matching request in its HTTP cache.
If there is a match, fresh or stale, it will be returned from the cache.
If there is no match, the browser will respond with a 504 Gateway timeout status.

I gave that a shot and it seems to work… but not as described. Rather than returning a 504 status, it throws a TypeError: NetworkError when attempting to fetch resource when I try this code:

fetch("/" + Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(), {
  cache: 'only-if-cached',
  mode: 'same-origin',
}).then((res) => {
  console.log('Fetch', res.status);
}).catch((err) => {
  console.error(err);
});

And the network tools in Firefox show NS_ERROR_DOCUMENT_NOT_CACHED for the request. So, getting warmer, but where’s this 504 response the documentation talks about? Unfortunately the error thrown in code in that case doesn’t look specific enough for me to distinguish it from other sorts of errors.

I’ve tried throwing the code in <script> tags and running it on a local server, and with all extensions disabled, but am getting the same behavior. The documentation seems clear and direct yet the described behavior eludes me. I am mainly using Firefox 12.1.0 64-bit Windows.

HTML Cause hydration failed because the initial UI does not match what was rendered on the server?

Simply adding: <html lang='pt-br'>

to my component in _app.tsx

const Layout = (props: ILayoutProps) => {
return (
  <html lang='pt-br'>
        <div className={`${inter.className} layout`}>
          <div className='w-full h-full flex flex-col justify-between'>
              <Left>
                {children}
              </Left>
              <Footer />
          </div>
        </div>
        </html>
  )
}

I get the error:

Unhandled Runtime Error
Error: Hydration failed because the initial UI does not match what was rendered on the server.

Warning: Expected server HTML to contain a matching <html> in <div>.

See more info here: https://nextjs.org/docs/messages/react-hydration-error

Why is that? Why is even different from server? Do I need to compile anything? But simply removing it, make the page work again. This is the main thing used in _app.tsx component.

How can I pull the first 10 elements with a specific class name from another html file and display them on my frontpage?

I have a list of movies in an html file (call it “movies.html”), which looks like this:

<div class="movie">Content 1</div>
<div class="movie">Content 2</div>
<div class="movie">Content 3</div>
...

I want to pull and display the first 10 divs with the class name “movie”, in my frontpage (“index.html”), so my frontpage would be automatically updated everytime I add another movie to the list in “movies.html”.

How can I achieve this?

html5 video player second playlist

need for my side a videoplayer with two paylisten get but not to run.
if you select a video from list one at beginning, nothing works, after selecting a video from list two the list one works.

html:

<label for="one">List1</label>
<select id="one">
  <option value="">- First List -</option>
  <option value="1.mp4">1</option>
  <option value="2.mp4">2</option>
  .......
</select>

<label for="two">List2</label>
<select id="two">
  <option value="">- Second List -</option>
  <option value="16.mp4">6</option>
  <option value="17.mp4">7</option>
.....
</select>

<br/><br/>

<video id="player" controls="true">
  <source id="mp4_src" src="1.mp4" type="video/mp4" />
</video>

js:

$(document).ready(function() {

  $('select').on('change', function() {
  var one = $('#one').val();
    var two = $('#two').val();
    if (!one || !two) return;
    change($(this).val());
  });

});


function change(sourceUrl) {
  var video = document.getElementById("player");
  var source = document.getElementById("mp4_src");

  video.pause();

  if (sourceUrl) {
    source.src = sourceUrl;
    video.load();
    video.play();
  }
}   

Tumblr Theme Development – Loading and Manipulating Post Notes Appearance

I’m currently working on a Tumblr theme development project and could use some guidance. I know Tumblr theme development isn’t as common nowadays, but I’m stuck and hoping someone can shed some light.

Issue:
I’ve created a script to manipulate the appearance of post notes, mimicking the Tumblr dashboard with categories for reblogs, likes, and comments. However, I’m facing problems when attempting to load more notes.

A screenshot of the post notes from the main dashboard

Specifics:

  1. I’m unsure how to re-run the script that Tumblr uses when loading more notes.
  2. I need to re-assign the newly loaded notes to the script I created.

Example:
Notes are coming from this URL, and when inspecting the “Show more notes” text, there’s an inline script to dynamically load the next notes via onclick.

if(window.tumblrNotesLoaded)if(tumblrNotesLoaded(notes_html)==false)return;var more_notes_link=document.getElementById('more_notes_737590887394263041');var notes=more_notes_link.parentNode;notes.removeChild(more_notes_link);notes.innerHTML+=notes_html;if(window.tumblrNotesInserted)tumblrNotesInserted(notes_html);}};tumblrReq.open('GET','/notes/737590887394263041/ValQ0Ka2H?from_c=1700827272',true);tumblrReq.send();return false;"

Current Code:

HTML:

{block:Posts}
...

{block:PermalinkPage}
 <article class="posts__perma__tumblr" data-notes-url="{PostNotesURL}" id="notes">
     <!-- the notes will be dynamically inserted here -->
     <div class="posts__perma__tumblr"></div>
 </article>
{/block:PermalinkPage}

{/block:Posts}

JS (so long…)

 document.addEventListener("DOMContentLoaded", function () {
     separateNotesAndShow();
     loadNotesViaAjax();
 });
 
 // Function to load the notes via AJAX
 // the URL comes from {PostNotesURL}
 // e.g https://fukuotest.tumblr.com/notes/737590887394263041/ValQ0Ka2H
 async function loadNotesViaAjax() {
     var nextNotesURL = document
         .querySelector(".posts__perma__tumblr")
         .getAttribute("data-notes-url");

     if (nextNotesURL) {
         try {
             var response = await fetch(nextNotesURL);
             if (response.status >= 200 && response.status < 300) {
                 var notesHtml = await response.text();
                 tumblrNotesLoaded(notesHtml);
             } else {
                 console.error("Error loading more notes");
             }
         } catch (error) {
             console.error("Fetch error:", error);
         }
     }
 }

 // Function to handle the loading of new notes
 function tumblrNotesLoaded(notes_html) {
     const newNotesContainer = document.createElement("div");
     newNotesContainer.className = "posts__notes__temporary";
     newNotesContainer.innerHTML = notes_html;

     // Extract the notes and update the nextNotesURL for potential further loading
     let newNoteElements =
         newNotesContainer.querySelectorAll("ol.notes > li.note");

     // Append the new notes to their respective categories
     const reblogNotes = [];
     const likeNotes = [];
     const replyNotes = [];
     newNoteElements.forEach((noteElement) => {
         if (noteElement.classList.contains("reblog")) {
             reblogNotes.push(noteElement);
         } else if (noteElement.classList.contains("like")) {
             likeNotes.push(noteElement);
         } else if (noteElement.classList.contains("reply")) {
             replyNotes.push(noteElement);
         }
     });

     appendNewNotes("reblog", reblogNotes);
     appendNewNotes("like", likeNotes);
     appendNewNotes("reply", replyNotes);
 }

 function appendNewNotes(category, newNotes) {
     const container = document.querySelector(`.posts__notes__${ category }`);
     newNotes.forEach((note) => {
         container.appendChild(note);
     });
 }

 function separateNotesAndShow() {
     var reblogNotes = [];
     var likeNotes = [];
     var replyNotes = [];

     var noteElements = document.querySelectorAll("ol.notes > li.note");
     var noteContainer = document.querySelector("ol.notes");
     var noteLoads = document.createElement("div");
     noteLoads.className =
         "posts__notes__load flex flex--align-center flex--justify-center";

     var postsPerma = document.querySelector(".posts__perma__tumblr");

     noteElements.forEach(function (noteElement) {
         if (noteElement.classList.contains("reblog")) {
             reblogNotes.push(noteElement);
         } else if (noteElement.classList.contains("like")) {
             likeNotes.push(noteElement);
         } else if (noteElement.classList.contains("reply")) {
             replyNotes.push(noteElement);
         } else if (noteElement.classList.contains("more_notes_link_container")) {
             noteLoads.appendChild(noteElement);
         }
     });

     createTabButtons();

     // Wrap the notes into a single container
     var notesContainer = document.createElement("div");
     notesContainer.className = "posts__notes__container";

     showNotes("reblog", reblogNotes, notesContainer);
     showNotes("like", likeNotes, notesContainer);
     showNotes("reply", replyNotes, notesContainer);

     postsPerma.appendChild(notesContainer);
     postsPerma.appendChild(noteLoads);

     // Show the reblog notes by default, and hide the others
     showCategory("reblog");
 }

 function createTabButtons() {
     var categories = ["reblog", "like", "reply"];
     var tabsContainer = document.createElement("div");

     tabsContainer.className = "posts__notes__button";

     categories.forEach(function (category) {
         var tabButton = document.createElement("button");
         var notesCount = document.querySelectorAll(
             ".posts__notes__" + category + " > li.note"
         ).length;

         var svgPath = getSVGPath(category);

         tabButton.innerHTML =
             ' <svg fill="currentColor" stroke="1" viewBox="0 0 20 18" width="18px" height="18px" class="margin--right-10">' +
             svgPath +
             '</svg> (' +
             notesCount +
             ') ' +
             category;

         tabButton.className =
             "posts__notes__button-tabs | posts__notes__button-" + category;
         tabButton.id = category + "-button";
         tabButton.addEventListener("click", function () {
             return showCategory(category);
         });
         tabsContainer.appendChild(tabButton);
     });

     var postsPerma = document.querySelector(".posts__perma__tumblr");
     postsPerma.appendChild(tabsContainer);

     var reblogButton = document.getElementById("reblog-button");
     reblogButton.classList.add("active");
 }



 function showCategory(category) {
     var allContainers = document.querySelectorAll(
         ".posts__notes__container > div"
     );
     allContainers.forEach(function (container) {
         container.style.display = "none";
     });

     var allButtons = document.querySelectorAll(".posts__notes__button > button");
     allButtons.forEach(function (button) {
         button.classList.remove("active");
     });

     var selectedContainer = document.querySelector(
         ".posts__notes__" + category
     );
     selectedContainer.style.display = "block";

     var selectedButton = document.getElementById(category + "-button");
     selectedButton.classList.add("active");
 }

 function showNotes(category, notes, container) {
     var notesContainer = document.createElement("div");
     notesContainer.className = "posts__notes__" + category;
     notes.forEach(function (note) {
         notesContainer.appendChild(note);
     });
     container.appendChild(notesContainer);
 }

 function getSVGPath(category) {
     switch (category) {
     case "like":
         return 'M14.658 0c-1.625 0-3.21.767-4.463 2.156-.06.064-.127.138-.197.225-.074-.085-.137-.159-.196-.225C8.547.766 6.966 0 5.35 0 4.215 0 3.114.387 2.162 1.117c-2.773 2.13-2.611 5.89-1.017 8.5 2.158 3.535 6.556 7.18 7.416 7.875A2.3 2.3 0 0 0 9.998 18c.519 0 1.028-.18 1.436-.508.859-.695 5.257-4.34 7.416-7.875 1.595-2.616 1.765-6.376-1-8.5C16.895.387 15.792 0 14.657 0h.001zm0 2.124c.645 0 1.298.208 1.916.683 1.903 1.461 1.457 4.099.484 5.695-1.973 3.23-6.16 6.7-6.94 7.331a.191.191 0 0 1-.241 0c-.779-.631-4.966-4.101-6.94-7.332-.972-1.595-1.4-4.233.5-5.694.619-.475 1.27-.683 1.911-.683 1.064 0 2.095.574 2.898 1.461.495.549 1.658 2.082 1.753 2.203.095-.12 1.259-1.654 1.752-2.203.8-.887 1.842-1.461 2.908-1.461h-.001z';

     case "reblog":
         return 'M12.8.2c-.4-.4-.8-.2-.8.4v2H2c-2 0-2 2-2 2v5s0 1 1 1 1-1 1-1v-4c0-1 .5-1 1-1h9v2c0 .6.3.7.8.4L17 3.6 12.8.2zM4.2 17.9c.5.4.8.2.8-.3v-2h10c2 0 2-2 2-2v-5s0-1-1-1-1 1-1 1v4c0 1-.5 1-1 1H5v-2c0-.6-.3-.7-.8-.4L0 14.6l4.2 3.3z';

     case "reply":
         return 'M8.7 0C4.1 0 .4 3.7.4 8.3c0 1.2.2 2.3.7 3.4-.2.6-.4 1.5-.7 2.5L0 15.8c-.2.7.5 1.4 1.2 1.2l1.6-.4 2.4-.7c1.1.5 2.2.7 3.4.7 4.6 0 8.3-3.7 8.3-8.3C17 3.7 13.3 0 8.7 0zM15 8.3c0 3.5-2.8 6.3-6.4 6.3-1.2 0-2.3-.3-3.2-.9l-3.2.9.9-3.2c-.5-.9-.9-2-.9-3.2.1-3.4 3-6.2 6.5-6.2S15 4.8 15 8.3z';

     default:
         return '';
     }
 }

What I’ve Achieved So Far:
I’ve structured the HTML and JS to handle note separation and loading more notes via AJAX. You can find the demo in the provided test blog.


Reference


Any assistance would be greatly appreciated!

And I deeply apologize in advance if the question appears to be too complex as it’s my first time asking a question here!

Request for Help:
I’m looking for guidance on re-running the script for loading more notes and re-assigning them correctly. There is a similar question on 2012 Running a function when loading more notes in Tumblr but still have no idea how to append the new notes

  • An approach to dynamically load more new notes via AJAX
  • Able to implement the function without an issue

Is javascript browser cache essentially a key/value store with the key the server path of the object and the value the requested object?

I’m just wondering if I preload a file in javascript with an async/await fetch, then later in the code I submit a request to fetch that file again…will any http requests to that path return from the javascript cache first?

This would essentially make the js cache a key/value cache with the key being the server side path and the value being the file.

Any caveats I should be aware of?

Needing a way to do conditional logic for products in woocommerce

I have several products and some of them are variable products. I need a way to have it shown on the front end that when a customer picks a certain option it shows other options but hides the ones that aren’t needed. For instance, I have a product that is a rebuild kit. There are many variations and attributes. The attributes are gauge, manufacturer, model, shot, and style. Not all of the products use the shot and the style attributes, so I need to hide those when that certain variation is chosen. I have added an image image of variations to show what I am talking about. the x’s are the attributes that I need to hide when that variation is chosen. I have searched for plugins to help with this but haven’t been successful. It seems that this needs to be custom coded.

I have tried several plugins and they are only for new products. I dont want to have to redo every product on the site that needs this functionality.

Where is the mistake in this JavaScript code? [closed]

I don’t understand the mistake when I work on b and c variables…

Github Copilot did the homework example, but in the b and c examples I worked and it tells me that is wrong.

Would you like to tell me the mistake?

PS: I worked on a example and I think is good, what do you think?

Thank you!

let a = -3;
let b = 7;
let c = 10;
let homework = 67;

if (a > 0) {
    console.log(`A is positive`);
} else {
    if (a === 0) {
        console.log(`A is zero`)
    } else {
        if (a < 0) {
            console.log(`A is negative`);
        }
    }
}

if (b) {
    console.log(`B is positive`);
} else {
    if (b === 0) {
        console.log(`B is zero`)
    } else {
        if (b < 0) {
            console.log(`B is negative`);
        }
    }
}

if (c) {
    console.log(`C is positive`);
    if (c === 0) {
        console.log(`C is zero`);
        if (c < 0) {
            console.log(`C is negative`);
        }
    }
}

if (homework) {
    console.log(`The student completed at least one homework`);
    if (homework > 50) {
        console.log(`The student completed at least 50 homeworks`);
    }
} else {
    console.log(`The student didn't complete a homework`);
}

How to access the element in a pop-up window in JavaScript?

In a webpage not created by me, there are many buttons in it.

I need to do the following tasks:

  1. Click one button(class is test) in the page, a new window will pop-up.
  2. Click the button(class is dotest) in the new pop-up window.
  3. Repeat step 1 to 2 until all the buttons in the page have been clicked.

I want to use JavaScript in Chrome console to automate the above task.

Below is my code:

var buttons = document.getElementsByClassName('test');

for (button of buttons) {
  button.click();
}

When button.click() is invoked, the pop-up window will appear. However, since the window is not created by me, how can I access the button(class dotest) in it(like this one)

Check element(s) before mutation

I’m working on my first more “complex” jQuery code. As a mutation observer only looks for changes I need to to something on the element with a specified class (“active”) on page load and then the same thing again on every other element that get’s the class (“active”). Currently I’m writing duplicate code (“Do something x”) which surely is not a good practice. That’s what I currently have so far.

jQuery(document).ready(function($) {

 var tabs = document.querySelectorAll(".tab-content");
 var active = 'active';

 $(tabs).each(function(index){

  //Check for the active tab on page load
  if($this).hasClass(classtowatch)) { //Do something x }

  //Mutation Observer for getting the active tab if tab changes
  var target = this;
  var config = {attributes: true};
  var prevClassState = target.classList.contains(active);
  var observer = new MutationObserver(function(mutations) {
   mutations.forEach(function(mutation) {
    if(mutation.attributeName == "class"){
     var currentClassState = mutation.target.classList.contains(active);
     if(prevClassState !== currentClassState){
      prevClassState = currentClassState;
              
      // Active Tab  
      if(currentClassState) {               
        // Do Something x
      }
      //Every other tab           
      else {}
      }
     }
    });
  });

  });
});