Typeform Integration Issue: “form.typeform.com refused to connect.” in React

I’ve integrated Typeform into my React application using the @typeform/embed-react package, but I’m encountering an issue. The error message I’m receiving is:

form.typeform.com refused to connect.

The browser’s network status console also shows:

(blocked:NotSameOriginAfterDefaultedToSameOriginByCoep)

What I’ve found out about this error: The NotSameOriginAfterDefaultedToSameOriginByCoep error typically indicates a Cross-Origin Embedder Policy (COEP) issue. It happens when the resource being requested does not have the proper headers to allow cross-origin resource sharing (CORS) and is therefore blocked by the browser’s security policies. This usually occurs when the resource does not explicitly grant permission for your site to embed it, due to differing origins.

Here is the relevant part of my React code:

import { Widget } from '@typeform/embed-react';

const Form = () => {
  return (
    <Widget
      className="my-form"
      id={form-id}
      style={{ width: '100%', height: '65vh' }}
    />
  );
};

export default Form;

This what I am seeing the web browser:
enter image description here

This is what we are seeing in Debugger:
enter image description here

Typeform Embed React Package Version: @typeform/embed-react v4.0.0

I’ve tried embedding the form using an iframe, but I still get the same error.

The browser’s network status console also shows:

(blocked:NotSameOriginAfterDefaultedToSameOriginByCoep)

I’ve tried checking the Typeform documentation and troubleshooting guides but haven’t found a solution yet. Has anyone encountered this issue before? How can I resolve this error and successfully integrate Typeform into my React app?

Any help would be greatly appreciated!

Is there a difference in js script in HTML vs external js script?

this is my first time posting so I might not be posting in the correct method. I’m trying to display the current value for a slider via an output. It doesn’t work when I put my script externally, but it does when I put it in the HTML file, so I’m confused.

**Here’s my initial code: **
(index.html)

<script src="js.js"></script>

<label for="max-invite">Select maximum number of invitations</label>
        <input type="range" name="max-invite" id="max-invite" min="1" max="30" value="10" step="1">
        <output class="invite-output" for="max-invite"></output>

(js.js)

const invite = document.querySelector('#max-invite');
      const output = document.querySelector('.invite-output');

      document.addEventListener('DOMContentLoaded', function(){
        output.textContent = invite.value;
      }) 

      invite.addEventListener('input', function() {
        output.textContent = invite.value;
      });

… and there is no display for the output.
I pasted the script direct onto the HTML file and it worked.
Is there a difference? Is there something I need to change to make the external script method work? TIA.

How do you display a table with hundreds (maybe more than 200) of pages using Datatables?

In Datatables, there are lot of pagination style and options, but the examples the provide are just up to 6 pages like this.

So far I usually use my own pagination (not datatables) with the “first page”, “second page”, dots between the second page and the current page, and then the current page. Likewise for the last page.

pagination I usually use

I started getting interested to Datatables because it fast in table built-in search box (even though it was poor in SQL stuffs).

This is one of the reasons why I can’t use Datatables on my web app.

I don’t know if it’s subjective or not. I just want to know how people use pagination with 400 pages with Datatables.

How can I handle complex nested data transformations in TypeScript using lodash?

I’m working on a TypeScript project where I need to perform complex transformations on deeply nested JSON data. I’m using lodash for utility functions, but I’m struggling with the following scenario:

{
  "users": [
    {
      "id": 1,
      "name": "Alice",
      "details": {
        "age": 25,
        "address": {
          "city": "Wonderland",
          "postalCode": "12345"
        }
      }
    },
    {
      "id": 2,
      "name": "Bob",
      "details": {
        "age": 30,
        "address": {
          "city": "Builderland",
          "postalCode": "67890"
        }
      }
    }
  ]
}

I need to:

  • Flatten the structure so that each user’s data is a single object with properties including the user’s address in a flattened format.
  • Transform the data into a new structure where the user’s postalCode is used as the key and the value is an object containing name, age, and city.

Questions:

  • Are there more efficient ways to flatten and transform this data using lodash?

  • How can I improve the readability and maintainability of this code, especially if the data structure becomes more complex?

Here’s what I’ve tried:

import _ from 'lodash'; 

const nestedData = {
  users: [
    {
      id: 1,
      name: "Alice",
      details: {
        age: 25,
        address: {
          city: "Wonderland",
          postalCode: "12345"
        }
      }
    },
    {
      id: 2,
      name: "Bob",
      details: {
        age: 30,
        address: {
          city: "Builderland",
          postalCode: "67890"
        }
      }
    }
  ]
};

// Flattening data
const flattenedData = _.flatMap(nestedData.users, user => ({
  id: user.id,
  name: user.name,
  age: user.details.age,
  city: user.details.address.city,
  postalCode: user.details.address.postalCode
}));

console.log('Flattened Data:', flattenedData);

// Transforming data
const transformedData = _.mapValues(
  _.keyBy(flattenedData, 'postalCode'),
  ({ name, age, city }) => ({ name, age, city })
);

console.log('Transformed Data:', transformedData);

Google Charts: Customize Date Format on Horizontal Axis

I have a google Line Chart which pulls data from a MySQL database. The very first column is in timestamp format, i.e. “1999-06-15 20:49:00” and is displayed along the horizontal axis of the Line Chart. The problem I have is that I can’t get the above timestamp to display as just the year, i.e. “1999” on the horizontal axis instead of “1999-06-15 20:49:00”.

I have the following line of code in my chart options hAxis: {title: 'Year', format: 'yyyy'}, which I assumed would give me the date formatted as “yyyy’ on the horizontal axis. However the date still shows in the above format, i.e. yyyy-mm-dd hh:mm:ss along the horizontal axis instead of yyyy.

My Line Chart code is as follows:

<script src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      
google.charts.load('current', {packages: ['corechart']}).then(drawChart);
        
        function drawChart() {
            var data = google.visualization.arrayToDataTable([
                //['class Name','Highest Annual Observed Tide','Highest Astronomical Tide','Highest Annual Predicted Tide','Number of High Tides > HAT'],
                ['Data',{type: 'number', label: 'Highest Annual Observed Tide'}, {type: 'number', label: 'Highest Astronomical Tide'},{type: 'number', label: 'Highest Annual Predicted Tide'},{type: 'number', label: 'Number of High Tides >= HAT'}],
                <?php
                $con = mysqli_connect('localhost','sealevel_Temp','Stackoverflow','sealevel_NZ');

                 $query = "SELECT * FROM `Tides` WHERE Location = 'Auckland'";
                 $exec = mysqli_query($con,$query);
                 while($row = mysqli_fetch_array($exec)){
                    //echo "['".date("Y",strtotime($row['Timestamp']))."',".$row['Highest Annual Observed Tide'].",".$row['Highest Astronomical Tide'].",".$row['Highest Annual Predicted Tide'].",".$row['Observed High Tides > HAT']."],";
                    echo "['".$row['Timestamp']."',".$row['Highest Annual Observed Tide'].",".$row['Highest Astronomical Tide'].",".$row['Highest Annual Predicted Tide'].",".$row['Observed High Tides > HAT']."],";
                 }
                ?>
            ]);
            
            var formatMSL = new google.visualization.NumberFormat({pattern: '# mm'});
               // format MSL data into mm.
               formatMSL.format(data, 1);
               formatMSL.format(data, 2);
               formatMSL.format(data, 3);

            var options = {
                fontSize: '20',
                title: 'Auckland Extreme Tides Summary', 
                titleTextStyle: {fontSize: 20, fontName: 'Arial', color: 'Black', bold:'True'},
                hAxis: {title: 'Year', format: 'yyyy'},
                height: 600,
                chartArea: {height: '75%', width: '80%', left: 100, right: 100},
                legend: {position: 'top', alignment: 'start', textStyle: {fontSize: 8, fontName: 'Helvetica'}, maxLines: 5},
                colors: ['blue'],
                tooltip: {isHtml: true},
                // Gives each series an axis name that matches the Y-axis below.
                series: {
                    0: {targetAxisIndex: 0, color:'blue'},
                    1: {targetAxisIndex: 0, color:'gray'},
                    2: {targetAxisIndex: 0, color:'#0099C6'},
                    3: {targetAxisIndex: 1, color:'navy'},
                    },
                vAxes: {
                    // Adds titles to each axis.
                    0: {title: 'Height above Chart Datum (mm)', viewWindow:{min: 3500, max: 4150}, format:'###0'},
                    1: {title: 'Number of Observed High Tides > HAT', viewWindow: {min: 0, max: 2}},
                    },  
                theme: 'material'
                        };
            var chart = new google.visualization.LineChart(document.getElementById("AucklandChart_div"));
            chart.draw(data,options);
        }
    </script>
<body>
 <div id="AucklandChart_div"></div>
</body>

Using the card hover effect with the bootstrap modal causes issues

I am currently designing a webpage using bootstrap and EJS. I want to create a modal window when one button is clicked to show additional information, and when an X button or “close” button is pressed, the modal window is closed.
However, the transform effect inside the card:hover css effect is messing up the modal window.
For starters, here’s the rough code

<%- include('_header'); -%> << header includes Bootstrap css, js and Font Awesome css.
<style>
  /* Card Style */
  .card {
    border-radius: 15px;
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    transition: all 0.3s ease;
  }
  .card:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 12px rgba(0,0,0,0.15);
  }
  .card-header {
    background-color: #007bff;
    color: white;
    border-top-left-radius: 15px;
    border-top-right-radius: 15px;
  }
  .badge-custom {
    font-size: 0.9em;
    padding: 8px 12px;
    border-radius: 20px;
  }
  /* Modal Style */
  .modal-header {
    border-bottom: 1px solid #dee2e6;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .modal-body {
    padding: 2rem;
  }
  .modal-footer {
    border-top: 1px solid #dee2e6;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
  
</style>

...

<div class="container mt-5">

...

<div class="row">
    <div class="col-md-6 mb-4">
      <div class="card bg-light">
        <div class="card-header">
          <h5 class="card-title mb-0">고객</h5>
        </div>
        <div class="card-body">
          <ul class="list-group list-group-flush">
            <% project.consumers.forEach(consumer => { %>
              <li class="list-group-item bg-light">
                <i class="fas fa-user-tie me-2"></i>
                <%= consumer.name %>
                <button type="button" class="btn btn-link" data-bs-toggle="modal" data-bs-target="#consumerModal<%= consumer.id %>">
                  <i class="fas fa-info-circle"></i>
                </button>

                <!-- Modal Start -->
                <div class="modal fade" id="consumerModal<%= consumer.id %>" tabindex="-1" aria-labelledby="consumerModalLabel<%= consumer.id %>" aria-hidden="true">
                  <div class="modal-dialog">
                    <div class="modal-content">
                      <div class="modal-header">
                        <h5 class="modal-title" id="consumerModalLabel<%= consumer.id %>"><%= consumer.name %>의 상세 정보</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                      </div>
                      <div class="modal-body">
                        <% Object.entries(consumer.custom_attributes).forEach(([attrKey, attrValue]) => { %>
                          <p><strong><%= attrKey %>:</strong> <%= attrValue.content %></p>
                        <% }); %>
                      </div>
                      <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">닫기</button>
                      </div>
                    </div>
                  </div>
                </div>
                <!-- Modal End -->

              </li>
            <% }); %>
          </ul>
        </div>
      </div>
    </div>

...

</div>

So when I press the button below, a modal window should appear in the center of the screen.

                <button type="button" class="btn btn-link" data-bs-toggle="modal" data-bs-target="#consumerModal<%= consumer.id %>">
                  <i class="fas fa-info-circle"></i>
                </button>

However, the first results were as follows.

https://i.imgur.com/PysG6V1.gif

As you can see in the image, a modal window appears in two places, and it flickers so fast that I can’t press the button. I asked ChatGPT to solve this problem and he recommended using the following JS to temporarily disable the transform.

<script>
  document.addEventListener('DOMContentLoaded', function () {
    var cards = document.querySelectorAll('.card');
    var modals = document.querySelectorAll('.modal');

    modals.forEach(function(modal) {
      modal.addEventListener('show.bs.modal', function () {
        cards.forEach(function(card) {
          card.style.transform = 'none';
        });
      });
      
      modal.addEventListener('hidden.bs.modal', function () {
        cards.forEach(function(card) {
          card.style.transform = '';
        });
      });
    });
  });
</script>

This eliminated the flickering modal window, but introduced another problem. The modal window would appear briefly in the div area that fetches the modal window, then disappear. Of course, many visitors will pass by without seeing this brief modal window, but I don’t think this is a good idea.

https://i.imgur.com/ysUP72n.gif

transform: translateY(-5px);

In my code, if just one line above inside the CSS is missing, everything works fine.

https://i.imgur.com/7K05E6Y.gif

I would gladly give up the effect of the card moving slightly when the user hovers over the card component to avoid this complication. However, the current situation doesn’t make logical sense to me, and I need to know why it’s happening so I can move on to the next step. Why is this happening?

Attempted to inject Javascript, attempted to modify CSS.

How to fix remote video not showing up on peerjs video call in nextjs?

In my next.js project, I’m trying to create a way to have p2p video calls; however, the remote caller’s video isn’t showing up. This works fin in different tabs but not different browsers or computers. I’m trying to figure out what the problem is. I tried using an open relay turn server, but that didn’t yield different results. Here is my code:

import { useEffect, useRef, useState } from 'react';
import Peer from 'peerjs';

const VideoChat = () => {
  const [peerId, setPeerId] = useState(null);
  const [remoteStreams, setRemoteStreams] = useState([]);
  const userVideoRef = useRef();
  const peerRef = useRef();

  useEffect(() => {
    const peer = new Peer(undefined, {
      path: '/myapp',
      host: 'my-server-url',
      port: 443,
      secure: true,
      config: {
        iceServers: [
          { url: 'stun:stun.l.google.com:19302' },
          {
            url: 'turn:open-relay-app-url.metered.live',
            credential: 'open-relay-API-key',
            username: 'open-relay-username'
          }
        ]
      }
    });

    peerRef.current = peer;

    peer.on('open', id => {
      setPeerId(id);
      console.log('My Peer ID:', id);
    });

    peer.on('call', call => {
      navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(localStream => {
        if (userVideoRef.current) {
          userVideoRef.current.srcObject = localStream;
          userVideoRef.current.play().catch(err => console.error('Error playing local video:', err));
        }
        call.answer(localStream);

        call.on('stream', remoteStream => {
          if (remoteStream && remoteStream.getTracks().length > 0) {
            const remoteVideo = document.createElement('video');
            remoteVideo.autoplay = true;
            remoteVideo.style.width = '300px';
            remoteVideo.style.height = '200px';
            document.getElementById('remote-videos').appendChild(remoteVideo);

            remoteVideo.srcObject = remoteStream;
            remoteVideo.play().catch(err => console.error('Error playing remote video:', err));

            setRemoteStreams(prev => [...prev, { id: call.peer, stream: remoteStream }]);
          } else {
            console.error('Remote stream not available.');
            alert('Error: Remote stream not available.');
          }
        });

        call.on('error', err => {
          console.error('Call error:', err);
          alert('Error during call: ' + err.message);
        });
      }).catch(err => {
        console.error('Error accessing media devices.', err);
        alert('Error accessing media devices: ' + err.message);
      });
    });

    peer.on('error', err => {
      console.error('Peer error:', err);
      alert('Error with peer connection: ' + err.message);
    });

    return () => {
      peer.destroy();
    };
  }, []);

  const callPeer = peerIdToCall => {
    navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(localStream => {
      if (userVideoRef.current) {
        userVideoRef.current.srcObject = localStream;
        userVideoRef.current.play().catch(err => console.error('Error playing local video:', err));
      }

      const call = peerRef.current.call(peerIdToCall, localStream);

      call.on('stream', remoteStream => {
        if (remoteStream && remoteStream.getTracks().length > 0) {
          const remoteVideo = document.createElement('video');
          remoteVideo.autoplay = true;
          remoteVideo.style.width = '300px';
          remoteVideo.style.height = '200px';
          document.getElementById('remote-videos').appendChild(remoteVideo);

          remoteVideo.srcObject = remoteStream;
          remoteVideo.play().catch(err => console.error('Error playing remote video:', err));

          setRemoteStreams(prev => [...prev, { id: peerIdToCall, stream: remoteStream }]);
        } else {
          console.error('Remote stream not available.');
          alert('Error: Remote stream not available.');
        }
      });

      call.on('error', err => {
        console.error('Call error:', err);
        alert('Error during call: ' + err.message);
      });
    }).catch(err => {
      console.error('Error accessing media devices.', err);
      alert('Error accessing media devices: ' + err.message);
    });
  };

  return (
    <div className="bg-red-500">
      <h1>Video Chat</h1>
      <p>Your Peer ID: <strong>{peerId}</strong></p>
      <div id="user-video">
        <video ref={userVideoRef} autoPlay muted style={{ width: '300px', height: '200px' }} />
      </div>
      <div id="remote-videos">
        {remoteStreams.length > 0 ? (
          remoteStreams.map(({ id, stream }) => (
            <div key={id}>
              <video
                ref={el => {
                  if (el) {
                    el.srcObject = stream;
                    el.play().catch(err => console.error('Error playing remote video:', err));
                  }
                }}
                autoPlay
                style={{ width: '300px', height: '200px' }}
              />
            </div>
          ))
        ) : (
          <p>No remote video streams available.</p>
        )}
      </div>
      <button onClick={() => callPeer(prompt('Enter peer ID to call:'))}>
        Call Peer
      </button>
    </div>
  );
};

export default VideoChat;

I’m using an express server. Here is my code for that:

// server.js
const { PeerServer } = require('peer');
const peerServer = PeerServer({ port: 9000, path: '/myapp' });

I am geting this error when I try to deploy Next Js 14 app And I am Not Using UsesearchParams Anywhere in my components and pages

ReferenceError: Element is not defined
    at 19328 (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverchunks3914.js:17:33442)
    at t (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverwebpack-runtime.js:1:128)
    at 58802 (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverchunks4706.js:1:2419)
    at t (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverwebpack-runtime.js:1:128)
    at 34589 (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverchunks4706.js:1:15455)
    at t (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverwebpack-runtime.js:1:128)
    at 75604 (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverappLoginpage.js:1:3101)
    at Object.t [as require] (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverwebpack-runtime.js:1:128)
    at require (D:ProjectsNextjsProjectsBlogProjectblog-projectnode_modulesnextdistcompilednext-serverapp-page.runtime.prod.js:16:18490)
    at I (D:ProjectsNextjsProjectsBlogProjectblog-projectnode_modulesnextdistcompilednext-serverapp-page.runtime.prod.js:12:94362) {
  digest: '3447373431'
}

Error occurred prerendering page "/Login". Read more: https://nextjs.org/docs/messages/prerender-error

ReferenceError: Element is not defined
    at 19328 (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverchunks3914.js:17:33442)
    at t (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverwebpack-runtime.js:1:128)
    at 58802 (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverchunks4706.js:1:2419)
    at t (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverwebpack-runtime.js:1:128)
    at 34589 (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverchunks4706.js:1:15455)
    at t (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverwebpack-runtime.js:1:128)
    at 75604 (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverappLoginpage.js:1:3101)
    at Object.t [as require] (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverwebpack-runtime.js:1:128)
    at require (D:ProjectsNextjsProjectsBlogProjectblog-projectnode_modulesnextdistcompilednext-serverapp-page.runtime.prod.js:16:18490)
    at I (D:ProjectsNextjsProjectsBlogProjectblog-projectnode_modulesnextdistcompilednext-serverapp-page.runtime.prod.js:12:94362)
ReferenceError: Element is not defined
    at 19328 (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverchunks3914.js:17:33442)
    at t (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverwebpack-runtime.js:1:128)
    at 58802 (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverchunks4706.js:1:2419)
    at t (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverwebpack-runtime.js:1:128)
    at 34589 (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverchunks4706.js:1:15455)
    at t (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverwebpack-runtime.js:1:128)
    at 25684 (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverappSignuppage.js:1:3118)
    at Object.t [as require] (D:ProjectsNextjsProjectsBlogProjectblog-project.nextserverwebpack-runtime.js:1:128)
    at require (D:ProjectsNextjsProjectsBlogProjectblog-projectnode_modulesnextdistcompilednext-serverapp-page.runtime.prod.js:16:18490)
    at I (D:ProjectsNextjsProjectsBlogProjectblog-projectnode_modulesnextdistcompilednext-serverapp-page.runtime.prod.js:12:94362) {
  digest: '2720037127'
}

I got this on vercel Please help me =

Can someone help me with Api’s in javascript

https://github.com/git-bbhu/weather-app

here is my github link i’m new to javascript i think the error is it’s showing 401 i have activated the api key and it’s still showing 401 please look at the js code and help me

I tried this after seeing this in a youtube video as expected it didn’t work so i asked a friend he ignored
me and tried looking for solutions in Chatgpt and didn’t so yeah i’m here

TypeError: THREE.BufferAttribute: array should be a Typed Array

I am trying to create a point cloud in threejs as:

const pcGeom = new THREE.BufferGeometry();
const rows = 100;
const columns = 3;
const vertices = [...Array(rows)].map(() => [...Array(columns)].fill(0));
for(let i = 0; i < rows; i++) {
  for (let j = 0; j < columns; j++) {
     vertices[i][j] = Math.random() * (2 - 0) + 0;
  }
}
pcGeom.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); // error at this line
const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
const pointCloud = new THREE.Mesh( geometry, material );

But this gives error(at line annotated above):

TypeError: THREE.BufferAttribute: array should be a Typed Array.

‘vertices’ is initialized, so I guess it’s typed, isn’t?

bootstrap 5 click inside dropdown should not open close the dropdown

I have the following code

<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.min.css">
<script src="https://code.jquery.com/jquery-3.7.1.slim.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>

</head>
<body>
<div class="dropdown">
  <button class="btn btn-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
    Dropdown button <i class="bi bi-x inside-button"></i>
  </button>
  <ul class="dropdown-menu">
    <li><a class="dropdown-item" href="#">Action</a></li>
    <li><a class="dropdown-item" href="#">Another action</a></li>
    <li><a class="dropdown-item" href="#">Something else here</a></li>
  </ul>
</div>
<script>
$('.inside-button').on('click', function(e) {
    console.log(new Date());
});
</script>
</body>
</html>

As you can see there is a bootstrap icon inside the button dropdown with a click event (by the class inside-button) the purpose of this functionality is to clear the content of the dropdown.

The problem is the dropdown still open and close when the icon is clicked, the click should only do the action without opening/closing the dropdown, how can I achieve this?

Note: I searched a lot inside stackoverflow before posting, this is for Bootstrap 5.

React Data – Data is Fetched, then Disappears

I have a Context & Provider that fetches user details, adds them to an object, and stores it in both a state variable and sessionStorage.

My goal is to provide this data to any widget that needs it without having to send it down via props.

I’ve tried to create a method whereby the userData can be fetched on demand simply by accessing userData – the API call is made automatically when/if necessary.


UserDataProvider.jsx:

import React, { useState, useContext, createContext } from "react";
import axios from 'axios'

const UserContext = createContext({})

export const theUser = () =>  useContext(UserContext)

const default_info = {
                            name: null,
                            age: null,
                            hobbies: [],
                        }


export const UserDataProvider = ( { children } ) => {


    const [ userData, setUserData ] = useState(getUserData())

    //gets user state from session storage OR a set of defaults OR from the server
    async function getUserData(){
        var data = JSON.parse(sessionStorage.getItem("userData"))
        if (data == "undefined" || data  == null){
           console.log("no data in session - fetching from server")
           data = await FetchUserData()
           return data 
        }
    
        console.log("Found data")
        console.table(data)
        return data


    }

    async function FetchUserData(){
        var body_json = {"getinfo": 1}
        try{
            await axios.post('/api/user_info', {
                headers: {
                    'Content-type':'application/json', 
                    'Accept':'application/json',
                    withCredentials: true
                },
                body: JSON.stringify(body_json)
            }).then((response) => {
                if (response.statusText == "OK"){
                    var userDataObject = {
                        name:   response.data['name'],
                        age:    response.data['savings'],
                        hobbies:  response.data['hobbies'],
                    }
                    
                    setUserData(userDataObject)
                    sessionStorage.setItem('userData', JSON.stringify(userDataObject))
                    return userDataObject
                }
                else return null

            });  
    
        } catch(error){
            console.error(error)
            return null
        }
    }

    const accessibleObjects = { 
       userData

    }


    return (
        <UserContext.Provider value={accessibleObjects}>
            { children }
        </UserContext.Provider>
    )
}

I have also wrapped components in the app…


main.jsx:

import { UserDataProvider } from './context/UserDataProvider.jsx';

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <AuthProvider>
      <UserDataProvider>
        <Router >
          <App />
        </Router>
      </UserDataProvider>
    </AuthProvider>
  </React.StrictMode>,
)

I can see the data being found in the console.

[vite] connecting...

client:614 [vite] connected.

UserDataProvider.jsx:36 Found data

UserDataProvider.jsx:37 

(index) Value
name    dave                            
age     35
hobbies     {…} {…} {…} {…} {…} {…} {…}
Object

...

However, it never gets used!

For example, the following widget will cause the data to be loaded (I can see it happen in the console), but when I access userData.name, nothing is there.

I get

Username is

in the body.



import { theUser } from '../context/UserProvider.jsx'

const ExampleComponent = () => {

   const { userData } = theUser()

   return(
    <>
    <h1>Username is {userData.name}</h1>
    </>

   )

}
export default ExampleComponent

I’m sure I’m missing something crucial – I fight with this a lot.

Can someone help me understand the intended way to manage data like this?

How to Create a Dynamic Tabbed Interface with HTML, CSS, and JavaScript?

I’m trying to create a dynamic tabbed interface for my website where users can click on different tabs to display different content sections. I’ve been able to create static tabs using HTML and CSS, but I’m not sure how to make them dynamic using JavaScript.

Here’s what I have so far:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tabbed Interface</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="tabs">
        <button class="tab-link active" onclick="openTab(event, 'Tab1')">Tab 1</button>
        <button class="tab-link" onclick="openTab(event, 'Tab2')">Tab 2</button>
        <button class="tab-link" onclick="openTab(event, 'Tab3')">Tab 3</button>
    </div>
    <div id="Tab1" class="tab-content">
        <h3>Tab 1</h3>
        <p>Content for Tab 1.</p>
    </div>
    <div id="Tab2" class="tab-content" style="display:none;">
        <h3>Tab 2</h3>
        <p>Content for Tab 2.</p>
    </div>
    <div id="Tab3" class="tab-content" style="display:none;">
        <h3>Tab 3</h3>
        <p>Content for Tab 3.</p>
    </div>
    <script src="script.js"></script>
</body>
</html>

CSS:

body {
    font-family: Arial, sans-serif;
}

.tabs {
    overflow: hidden;
    background-color: #f1f1f1;
    border-bottom: 1px solid #ccc;
}

.tab-link {
    background-color: inherit;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 14px 16px;
    transition: background-color 0.3s;
}

.tab-link:hover {
    background-color: #ddd;
}

.tab-link.active {
    background-color: #ccc;
}

.tab-content {
    display: none;
    padding: 6px 12px;
    border: 1px solid #ccc;
    border-top: none;
}

JavaScript:

function openTab(evt, tabName) {
    var i, tabcontent, tablinks;

    tabcontent = document.getElementsByClassName("tab-content");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }

    tablinks = document.getElementsByClassName("tab-link");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }

    document.getElementById(tabName).style.display = "block";
    evt.currentTarget.className += " active";
}

This code mostly works, but I’m running into a few issues:

  1. The default active tab doesn’t display its content until I click on another tab and then back.
  2. The CSS styles don’t seem to transition smoothly when switching tabs.

Can someone help me understand how to fix these issues or suggest a better approach to create a dynamic tabbed interface?

Thanks in advance!