How can I put data from API in to my HTML tag H1 and H2? [closed]

I am fetching data from an API and want to show this data into HTML tags H2 and H3. I have shared the code below.

<h2 class="setup-line" id="setup"></h2>
  <h3 class="punch" id="punchline"></h3>

async function generateJoke() {
  const apiUrl =
    "https://official-joke-api.appspot.com/jokes/programming/random";

  const response = await fetch(apiUrl);

  const data = await response.json();

  document.getElementById("setup").innerHTML = data.setup;
  document.getElementById("punchline").innerHTML = data.punchline;

  console.log(data);
}
generateJoke();

How to display error body on front end using axios

My fast api end point is here:

async def signup( credentials : signupcred ):
  try: 
   print(credentials.email,  credentials.password1, credentials.name )
   response = account.create(email= credentials.email, password= credentials.password1, name = credentials.name , user_id= ID.unique() )

   return {response}

  except Exception as e: 
         raise HTTPException(status_code= status.HTTP_403_FORBIDDEN)  # Return an appropriate error status code

on the front end, i want to print the response after an exception has been raised because the response explains the error well. I don’t want to send a http error code to the user.

my front end is :

const handlesignup = async (e: any) => {
  e.preventDefault();
  setLoading((loading) => !loading);
  try{
    const signupresponse = await axios.post('/api/signup', {'email': signupemail, 'password1': password1, 'name': name} );// Send as query paramers );
   // const loginresponse = await axios.post('/api/login', {email, password} )// Send as query paramers );
   // setIsloggedin(()=> true)
   router.replace('/dashboard') 
    setLoading((loading) => !loading)
}
catch (error){


  alert(error)

The console.log doesnt work because im using nextjs with fast api backend. I just want to print the response from the create function to the front end so users know why the function error has occurred. At the moment the alert shows: AxiosError: Request failed with status code 500

‘useStateValue’ is giving ‘TypeError: undefined is not iterable’

I was creating an Amazone clone for my project. While creating the checkout page, I got an TypeError.It pops due the “useStateValve()”, saying “undefined is not iterable”.I’m using the useStateValve to pull my data in dispatching process but this error won’t make it possible .I’ve tried everything and still unable to solve this issue.I’m making this project with reference of a youtube channel- clever programmer.Following is the code which creates the error, along with the code from where it is initiated.

import React from 'react';
import "./Product.css";
import { useState } from './StateProvider';


function Product({ id, title, image, price, rating }) {
    const [{ basket }, dispatch] = useStateValue();

    console.log("this is added to the basket");

    const addToBasket = () => {
       dispatch({
        type: "ADD_TO_BASKET",
        item: {
            id: id,
            title: title,
            image: image,
            price: price,
            rating: rating,
        },
       });
    };
    
  return (
    <div className='product'>
        <div className='product-info'>
            <p>{title}</p>
            <p className='product-price'>
                <small>$</small>
                <strong>{price}</strong>
            </p>
            <div className='product-rating'>
                {Array(rating).fill().map((_, i) => (
                    <p key={i}>⭐</p>
                ))}
            </div>
        </div>
        <img src={image} alt=''/>
        <button onClick={addToBasket}>Add to Basket</button>
    </div>
  )
}

export default Product
import React, { createContext, useContext, useReducer} from "react";

//Prepares the data layer
export const StateContext = createContext();

//Wrap our app and provide the data layer
export const StateProvider = ({ reducer, initialState, children }) => (
    <StateContext.Provider value={useReducer(reducer, initialState)}>
        {children}
    </StateContext.Provider>
);

//pull information from the data layer
export const useStateValue  = () => useContext(StateContext);
[image showing the error](https://i.stack.imgur.com/rBGxW.png)

I tried many ways but it isn’t helping me.It works as, whenever we tap the add to the basket in amazon app while buying any product the details of the product should go to the chechout page,.ie. the shopping cart.
PLease help me through this issue

Updating Scrollbar in Real-time for Draggable Circular Container in HTML Canvas with JavaScript

I’m developing a draggable circular container within a canvas in HTML and JavaScript, and I’m having difficulty getting the scrollbar to update automatically each time the user scrolls within the container. Although the container scrolls correctly, the scrollbar doesn’t reflect these changes in real-time. How can I solve this issue to ensure that the scrollbar synchronizes properly with the movement of the content within the circular container?

const canvas = document.getElementById('canvas');
const container = document.getElementById('container');
const ctx = canvas.getContext('2d');

const resizeCanvas = () => {
    canvas.height = container.clientHeight;
    canvas.width = container.clientHeight;
}

let containerHeight, containerScrollHeight,scrolled, docHeight, scrollPer;

const render = () => {
    containerHeight = container.offsetHeight;
    containerScrollHeight = container.scrollHeight;
    scrolled = container.scrollTop;
    scrollPer = scrolled / (containerScrollHeight - containerHeight);
    
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.lineWidth = 5;
    makeArc('#666666', canvas.width / 2, canvas.height / 2, canvas.height / 2.05, 0, 2 * Math.PI);
    makeArc('#000000', canvas.width / 2, canvas.height / 2, canvas.height / 2.05, ((container.scrollTop - 0.1) * 2) * Math.PI, (container.scrollTop * 2) * Math.PI);
};

const makeArc = (color, one, two, three, four, five) => {
    ctx.beginPath();
    ctx.strokeStyle = color;
    ctx.arc(one, two, three, four, five);
    ctx.stroke();
};


resizeCanvas();
render();
window.addEventListener('resize', function() {
    resizeCanvas();
    render();
});
container.addEventListener('scroll', render);
:root{
  --item-size: 40dvw;
}
*{
  box-sizing: content-box;
}
html {
  scrollbar-width:none;
  -ms-overflow-style:none;
  overflow-y:-moz-scrollbars-none
}
.hide-scrollbar::-webkit-scrollbar {
  width:0;
  display: none
}
body{
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  align-content: center;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
  background-color: rgba(185, 212, 235, 0.698);
}
section{
  border-radius: 50%;
  width: calc(var(--item-size) + 5.9px);
  height: calc(var(--item-size) + 5.9px);
  gap: 2px;
  position: relative;
  overflow: hidden;
}
main{
  display: grid;
  grid-auto-flow: row;
  width: 100%;
  height: 100%;
  gap: 2px;
  overflow: scroll;
  scrollbar-width: none;
  scroll-snap-type: y mandatory;
  scroll-behavior: auto;
  position: relative;
  box-sizing: border-box;
}
main>.item{
  background-color: aliceblue;
  border: 3px;
  border-color: black;
  border-style: dashed;
  border-radius: 50%;
  aspect-ratio: 1;
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-wrap: wrap;
  align-content: center;
  justify-content: center;
  scroll-snap-align: start;
}
.canvas{
  position: absolute; 
  right: 0px; top: 0px;
  border-radius: 50%;
  pointer-events: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <h1>Hi</h1>
<section class="scrollbar" id="container">
<main>
  <div class="item">
    <p>hola</p>
  </div>
  <div class="item">
    <p>hola</p>
  </div>
  <div class="item">
    <p>hola</p>
  </div>
</main>
<canvas width="100" height="100" class="canvas" id="canvas"></canvas>
</section>
</body>
</html>

Hide and show div based on incrementing select ID

I am trying to hide and show an input wrapped inside js/html dynamic table. The input shows only when an option is selected. I am trying to retain an array of OTHER option in case a client selects OTHER from different dynamic table rows.
The problem Im facing is that, its only working before adding another table row dynamically
Below is my html code

  <table class="table table-bordered table-striped table-hover" id="myTable">
    <tr>
      <td>
       <select class="form-control select2" id="selectId_1" name="myvalue[]" required>
        <option value="val 1">.......</option>
        <option value="Other">Other</option>
     </select>
     <input type="text" class="form-control other" id="other_1" name="other[]" class="form-control " placeholder="other category" ></td>
     <td><input autocomplete="off" class="form-control quantity" id="quantity_1" name="quantity[]" type="number"></td>
     <td>...</td>
   </tr>
 </table>

Here is the js code which seems to only work on the first row

     $('[id^=selectId_]').each(function (i) {
    i++;
    $(this).change(function () {
      if( $(this).val()==="Other"){
        $('#other_'+i).show();
        }
      else{
        $('#other_'+i).hide()
      }
    });
});

conflict betwen 2 php codes, using the metaslider plugin

I have this 2 code snippets for the WordPress plugin metaslider. The first one adds the “ken burns effect”, the second one disables the “pause on action” property. For some reason, the “pause on action” is messing the “ken burns effect” after some seconds, ¿What could be the problem? THANKS!

THE FIRST CODE

$slideshow_id = '33';

add_filter('metaslider_css_classes', function($classes, $id) use ($slideshow_id) {
    if ($id != $slideshow_id) return $classes;
    return $classes . ' kenburns-effect';
}, 10, 2);

add_filter('metaslider_css', function($css, $settings, $id) use ($slideshow_id) {
    if ($id != $slideshow_id) return $css;
    return $css . "
    .kenburns-effect .flexslider .slides,
    .kenburns-effect .flexslider .slides > li {
        overflow: hidden;
    }
    .kenburns-effect .flexslider .slides > li .kenburns-inner {
        background-size: cover;
        background-position: center;
        position: absolute;
        width: 100%;
        height: 100%;
        left: 0;
        top: 0;
    }
    .kenburns-effect .flexslider .slides img {
        opacity: 0;
    }
    .kenburns-effect .flexslider .slides > li.flex-active-slide .kenburns-inner {
        animation: kb-zoom-out {$settings['delay']}ms;  
    }
    @-webkit-keyframes kb-zoom-out {
        0% {
            transform: scale(1.3);
        }
        100% {
            transform: scale(1);
        }
    }";
}, 10, 3);

add_filter('metaslider_flex_slider_list_item_attributes', function($attributes, $slide, $id) use ($slideshow_id) {
    if ($id != $slideshow_id) return $attributes;
    $movements = ['center left', 'center center', 'center right', 'top left', 'top center', 'top right', 'bottom left', 'bottom center', 'bottom right'];
    $attributes['data-background'] = isset($slide['src']) ? $slide['src'] : '';
    $attributes['data-movement'] = $movements[array_rand($movements)];
    return $attributes;
}, 10, 3);

add_filter('metaslider_flex_slider_javascript', function($js, $id) use ($slideshow_id) {
    if ($id != $slideshow_id) return $js;
    return $js . ";window.jQuery('.kenburns-effect .slides .ms-image').each(function() {
        var background = $(this).data('background');
        var movement = $(this).data('movement');
        $(this).prepend("<div class='kenburns-inner' style='background-image:url(" + background + ");transform-origin:" + movement + "'></div>");
    });";
}, 10, 2);

THE SECOND CODE

function custom_metaslider_js() {

    $slideshow_id = '33';

    $js = "
    <script type='text/javascript'>
        jQuery(document).ready(function($) {
            $('.metaslider-{$slideshow_id}').flexslider({
                pauseOnAction: false
            });
        });
    </script>
    ";
    echo $js;
}
add_action('wp_footer', 'custom_metaslider_js');

Warning! Error encountered during contract execution [execution reverted] (Base Layer2)

I’m trying to execute a swap using Uniswap V2 SDK in a Node.js environment.
However, when I run the code below, I receive the following error:
“Warning! Error encountered during contract execution [execution reverted]”

async function createPair() {
  const pairAddress = Pair.getAddress(TOKEN, WETH9[TOKEN.chainId]);

  const pairContract = new ethers.Contract(pairAddress, UniswapV2PoolAbi, provider);

  const reserves = await pairContract['getReserves']();
  const [reserve0, reserve1] = reserves;

  const reserve0Parsed = BigInt(reserve0.toString()).toString();
  const reserve1Parsed = BigInt(reserve1.toString()).toString();

  const tokens = [TOKEN, WETH9[TOKEN.chainId]];
  const [token0, token1] = tokens[0].sortsBefore(tokens[1]) ? tokens : [tokens[1], tokens[0]];

  const pair = new Pair(
    CurrencyAmount.fromRawAmount(token0, reserve0Parsed),
    CurrencyAmount.fromRawAmount(token1, reserve1Parsed)
  );

  return pair;
}

async function swap() {
  const amountIn = ethers.parseEther('0.00001').toString();
  const slippageTolerance = new Percent('50', '10000');
  const to = WALLET_ADDRESS;
  const signer = new ethers.Wallet(WALLET_SECRET);
  const account = signer.connect(provider);
  const command = '0x08';
  const deadline = 2 * 10 ** 10;
  const fromEoa = true;

  const uniswap = new ethers.Contract(
    swapRouterAddress,
    [
      'function execute(bytes calldata commands, bytes[] calldata inputs, uint256 deadline) external payable returns (bytes[] memory outputs)',
    ],
    account
  );

  const pair = await createPair();
  const route = new Route([pair], WETH9[TOKEN.chainId], TOKEN);
  const trade = new Trade(
    route,
    CurrencyAmount.fromRawAmount(WETH9[TOKEN.chainId], amountIn),
    TradeType.EXACT_INPUT
  );

  const amountOutMin = trade.minimumAmountOut(slippageTolerance).toExact();

  const amoutOut = ethers.parseEther(amountOutMin);

  const pathData = ethers.solidityPacked(
    ['address', 'address'],
    [WETH9[ChainId.BASE].address, TOKEN.address]
  );

  const v2Calldata = ethers.AbiCoder.defaultAbiCoder().encode(
    ['address', 'uint256', 'uint256', 'bytes', 'bool'],
    [to, amountIn, amoutOut, pathData, fromEoa]
  );

  const tx = await uniswap.execute(command, [v2Calldata], deadline, {
    value: amountIn,
    gasPrice: ethers.parseUnits('0.15', 'gwei'),
    gasLimit: 100000,
    chainId: ChainId.BASE,
    from: WALLET_ADDRESS,
  });

  console.log(`Transaction hash: ${tx.hash}`);
  const receipt = await tx.wait();

  console.log(`Transaction was mined in block ${receipt.blockNumber}`);
}

*/

Here’s a brief overview of what the code does:

  1. Imports necessary Uniswap V2 SDK components and ethers.js.
  2. Sets up provider with a QuickNode HTTP endpoint.
  3. Defines wallet address and secret.
  4. Creates a swapRouterAddress and a TOKEN.
  5. Defines a swap function that executes a swap using Uniswap V2.
  6. Inside the swap function:
  • a. Sets up amountIn, slippage tolerance, recipient address, and signer.
  • b. Creates a Uniswap contract instance.
  • c. Calls createPair() to create a Uniswap pair.
  • d. Calculates trade details and encodes calldata.
  • e. Executes the swap with Uniswap’s execute() function.

I suspect the issue might be related to how I’m encoding the data or setting up
the transaction. Can someone help me understand why I’m getting this error
and how I can resolve it?

Also check some of my transactions:
https://basescan.org/tx/0x5a4ccdf8476eac2b41e00927cae6cb5817cff4acfb1c4746244ebd3d22784e9e
tenderly analyzer

Thanks!

Firebase DOMException when the sign up and sign in method is called

When the userCredential object is called in sign in or account creation methods an DOMexception is thrown

The user is successfully created, but cannot be used due to an exception


loginForm.addEventListener('submit', e => {

  e.preventDefault();

  

  const email = loginForm['login-email'].value;

  const password = loginForm['login-password'].value;

  

  signInWithEmailAndPassword(auth, email, password)

  .then((userCredential) => {

    // Signed in 

    const user = userCredential.user; //DOMException

  });

})```


[DOMException](https://i.stack.imgur.com/vluXg.jpg)

I tried to recreate the project and did not find information on the Internet 

How do I imitate this Ink Bleeding / Distressed Letterpress Print effect using CSS & JS?

I’m trying to imitate a distressed letterpress print using CSS &/ JS. Specifically, I like the grain and ink bleeding on vintage posters and I am hoping to recreate the effect in a website I’m developing. The site is running next.js 14 along with tailwindcss. Here is a photo of what I would like to achieve!

enter image description here

From what I am familiar with, we could use the webkit-background-clip effect to achieve the paper like effect on the text. That is to say:

<p className="text-mask text-8xl font-bold tracking-tight">ツバメ</p> <!-- I'm using tailwindcss here! -->
.text-mask {
  background: url("/public/bg.jpeg") 0 0 / cover no-repeat;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

Therefore, the paper like texture is relatively simple to achieve. My troubles arise in imitating the bleeding of ink on paper. For reference, here is a photo of simply the text and the bleeding ink.

with ink bleeding

Compare to this without the ink bleeding.

no ink bleeding

As I see the edges are much crisper than the bleeding ink. I have been trying to search for a way to recreate this bleeding ink effect but I cannot find anything similar online.

My current idea is to use a Gaussian blur filter filter: blur(4px) and somehow use the image-rendering: pixelated; CSS property by treating the text as an image. I don’t know if this will work because I am not able to recreate the specifics to my liking. If anything else works, please do let me know.

Vue computed prop change not being reflected in component if value references same object

example store:

const trigger = ref(true);
const prop = computed(() => {
  trigger.value;
  console.log('comp prop run'); // works!
  return some_big_object;
});

const doChange = () => {
   some_big_object[5000].text = 'abc';
   trigger.value = !trigger.value;
}

 return { prop, doChange }

in component if I call store.doChange, the computed function runs, but the component still displays the previous value (no updated)

if I change the return in computed function to return {... some_big_object}; then it updates everywhere!

It appears to be because Vue does some check for the value, if it has the same reference as the prev value, it will not re-render it…

Is there some other way around this? I’d like to avoid creating a copy of a large object.

select dropdown lists with the same options

I have a form where the user enters the number of lists ( dropdown lists ) all witth the same options and options are fetched from database. each list have default option ” select Testroom ” and when option is selected , it shouldn’t be available in the next list.
my problem is that after the option is selected , it doesnt appear as the default , instead it stays ” select a testroom ” . It worked without index and the testroom number ,
and after deselection it stays unavailable. and there are no errors or warnings so i don’t understand the mistakes.

import React, { useState, useEffect } from 'react';
import axios from 'axios';
function testroom() {
  const [formData, setFormData] = useState({
        
        testrooms: []
        
    });
  const [testroomCount, setTestRoomCount] = useState(1);
  const [testrooms, setTestRooms] = useState([]);
  const handleTestRoomCountChange = (e) => {
        const { value } = e.target;
        setTestRoomCount(parseInt(value));
        setFormData((prevState) => ({
            ...prevState,
            testrooms: Array.from({ length: parseInt(value) }, () => ''),
        }));
    };

    const handleTestRoomSelection = (index, e) => {
        const { value } = e.target;
        setFormData((prevState) => ({
          ...prevState,
          testrooms: value === ""
            ? [...prevState.testrooms].slice(0, index).concat([...prevState.testrooms].slice(index + 1)) // Remove room at index
            : [...prevState.testrooms].map((room, idx) => (idx === index ? value : room)),
        }));
              console.log("Updated formData.testrooms:", formData.testrooms); // Log the updated state
      };

  return (
    <div>
      <form>
        <div className="field" >
                        <label htmlFor='testroomCount'> Number of Test Rooms : </label>
                        <input type="number" id="testroomCount" name="testroomCount" value={testroomCount} onChange={handleTestRoomCountChange} min="1" max="5" />
                    </div>
                    {Array.from({ length: testroomCount }).map((_, index) => {
                    // Filter out the selected test rooms from the list of available test rooms
                    const availableTestRooms = testrooms.filter((room) => !formData.testrooms.includes(room._id));
                    return (
                        <div className="field" key={index}>
                            <label htmlFor={`testroom${index + 1}`}>Test Room {index + 1}:</label>
                            <select id={`testroom${index + 1}`} name={`testroom${index + 1}`} value={formData.testrooms[index]} onChange={(e) => handleTestRoomSelection(index, e)} required>
                                <option value="">Select a Test Room</option>
                                {availableTestRooms.map((testroom, idx) => (
                                    <option key={idx} value={testroom._id}  >
                                        {testroom.testroom}
                                    </option>
                                ))}  </select>  </div>   );  })}  </form> </div> )}
export default testroom;

How to make an “No condition” query in firebase database?

How can I write query to check if a field is existed in a document like in the attachment ? Currently in my code when I leave the operator empty the error message pops up “FirebaseError: Unknown field filter op.”

Pic 1
Pic 2

I did try many ways like !=, >= and <= but didn’t work because I’m querying more than one object key in a single query so I think the approach of using “No Condition” query seems to be more feasible

Resizing a Map with react-simple-maps in React

I’m attempting to display a map of France using react-simple-maps. However, I’m encountering an issue where the map appears too small. Despite trying various methods such as CSS adjustments, modifying width and height attributes and using ZoomableGroup, I haven’t been able to scale it up successfully. Could someone assist me in resolving this issue?

Here’s my code:

import { Page } from "@/components/ui/page";
import {
  ComposableMap,
  Geographies,
  Geography,
  ZoomableGroup,
} from "react-simple-maps";

const geoUrl =
  "https://france-geojson.gregoiredavid.fr/repo/departements.geojson";

export default () => {
  return (
    <Page className="gap-10 w-full">
      <Page.Header className="flex flex-col gap-4 items-start">
        <h1 className="mt-[70px] text-3xl">Carte</h1>
        <h2 className="text-xs text-dark opacity-65">Carte des departements</h2>
      </Page.Header>

      <Page.Body>
        <ComposableMap
          projectionConfig={{
            scale: 155,
          }}
          width={800}
          height={400}
          style={{ width: "100%", height: "auto" }}
        >
          <ZoomableGroup disablePanning zoom={1}>
            <Geographies geography={geoUrl}>
              {({ geographies }) =>
                geographies.map((geo) => (
                  <Geography key={geo.rsmKey} geography={geo} />
                ))
              }
            </Geographies>
          </ZoomableGroup>
        </ComposableMap>
      </Page.Body>
    </Page>
  );
};

Here’s the image:
enter image description here