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!

Calculo de Frete / Freight Calculation

Estou programando em nextjs e estou com dificuldade na funcionalidade de calcular frete de um ecommerce que estou fazendo, olhe a documentação do correios, mas achei muito massiva, e a do melhor envio não consegui implementar.

Alguem poderia me ajudar a fazer essa implantação ? Sugerindo video, documentação ou dando um help de alguma maneira…

English
I’m programming in nextjs and I’m having difficulty with the functionality of calculating shipping for an ecommerce I’m doing, look at the documentation of the post office, but I found it too massive, and the best shipping I couldn’t implement.

Could someone help me to do this implementation? Suggesting video, documentation or giving a help in some way…

Já tentei implantar com a documentação do correios e do melhor envio e não consegui, então estou na estaca 0 novamente kkk não sei o que fazer.

English
I’ve tried to implement it with the documentation of the post office and the best shipping and I couldn’t, so I’m at stake 0 again lol I don’t know what to do.

Calling Python Api from javascript file not working

While trying to retrieve data from the python api i created below, i get ‘Failed to load resource: the server responded with a status of 500 (INTERNAL SERVER ERROR)’ error line 3 of the js file. I tried restarting and going through the process again but that resulted in the same thing.

app.js

/*async function fetchdata(){*/
    try {
        const response = await fetch('http://127.0.0.1:5000/api/get_data');
        const data = await response.json();  // Convert response to JSON

        console.log('Data:', data);

        // return data; 
    } catch (error) {
        console.error('Error:', error);
    }
/*}
fetchdata();*/

app.py

@app.route('/api/get_data', methods=['GET'])
def get_data():
    form = loginForm()
    print('hello')
    data = {
        "ownsPython": str(User.query.filter_by(username = form.username.data).first().javascriptOwner),
        "ownsJava" : str(User.query.filter_by(username = form.username.data).first().pythonOwner),
        "ownsPython" : str(User.query.filter_by(username = form.username.data).first().ownsJavascript)
    }
    return jsonify(data)

React App won’t render after importing auth from firebase

Vite, React, and Tailwind.
When I ran my project on the browser with auth from firebase imported, my app wouldn’t load. Now, what I realized is that when I put the import auth from 'firebase/auth' at the end of the code the app will still load. So, I assume that the import takes more time and the solution is something correlated with asynchronous importing. Alas, I still haven’t founded the right code to fix it.

Here’s my code:

firebase.jsx

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
import { getAuth } from "firebase/auth";

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "####",
  authDomain: "####.firebaseapp.com",
  projectId: "###",
  storageBucket: "###",
  messagingSenderId: "####",
  appId: "####",
  measurementId: "####"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
export const auth = getAuth();

SignUp.jsx

This is where I want to put the sign up functioning. So, when line one is inputted, the app would crash. However, when it is put on the last line of code, it won’t. I wouldn’t be able to write the code properly if the import was in the last line.

import auth from '../firebase/firebase'
export default function SignUp(){
    return (
        <div className="rounded-xl w-2/5 flex-1 absolute h-2/4 bg-dark items-center left-2/4 top-2/4 -translate-y-2/4 -translate-x-2/4 ">
            <form action="">
                <h2 className="text-white text-3xl flex-1 font-mono font-bold text-center">Sign Up</h2>
                <input type="text" /> 
            </form>
        </div>
    )
}

I tried asynchronous importing using this syntax that I found on stackexchange but it didn’t work.

(async () => {

  const { getAuth } = await import('firebase/auth');

})();

I also tried to put the import { getAuth } from "firebase/auth"; on the SignUp file and continue everything from there but still didn’t work.

How to share an access with Authorized users in Apps Script Web App without them giving access to Google Sheets?

How to give permission to Authorized users to use the apps script web app without them giving access the google sheets? I am so confused right now. Please help me…
So I also create AuthorizedUsers sheet where there is the list of the emails of the authorized people I want to give access. So when they click the link of the web app the authorized users should be redirected to the index page while the non authorized users should get the message “You are not authorized to access this application.” but the issue here is that, when the other users tried to access the web app even if their email is in the AuthorizedUsers sheet they are still getting a message like this “Exception: You do not have permission to access the requested document. (line 39, file “Code”)”

This is the code I tried.
In the manage deployments I’ve set the following:

Execute as:
*User accessing the web app *

Who has access:
Anyone with Google account

Code.gs

function doGet(e) {
  // Check if the event object e is defined and has parameter
  var page = (e && e.parameter) ? e.parameter.page || 'index' : 'index'; // Default to 'index' if no page is specified or e is undefined

  var userEmail = Session.getActiveUser().getEmail();
  Logger.log("User Email from Session: " + userEmail); // Debugging line

  if (isAuthorized(userEmail)) {
    logUserEmail(userEmail);
    return HtmlService.createTemplateFromFile(page).evaluate();
  } else {
    // Redirect to an unauthorized access page or show an error message
    return HtmlService.createHtmlOutput("You are not authorized to access this application.");
  }
}

function loadIndex(e) {
  // Check if the event object e is defined and has parameter
  var page = (e && e.parameter) ? e.parameter.page || 'index' : 'index'; // Default to 'index' if no page is specified or e is undefined

  var userEmail = Session.getActiveUser().getEmail();
  Logger.log("User Email from Session: " + userEmail); // Debugging line

  if (isAuthorized(userEmail)) {
    logUserEmail(userEmail);
    return HtmlService.createTemplateFromFile(page).evaluate();
  } else {
    // Redirect to an unauthorized access page or show an error message
    return HtmlService.createHtmlOutput("You are not authorized to access this application.");
  }
}

function logUserEmail(email) {
  var email = Session.getActiveUser().getEmail();
  Logger.log("User Email: " + email);
}

function isAuthorized(email) {
  var sheet = SpreadsheetApp.openById('13dStidKhr3EcvDUZTZWxFVc5N2rQkfbGySclp0JqNTI').getSheetByName('AuthorizedUsers');
  var data = sheet.getRange('A:A').getValues(); // Get all email addresses in column A
  var emails = data.flat().filter(String); // Flatten and remove empty values

  Logger.log("Authorized Emails: " + JSON.stringify(emails)); // Debugging line
  return emails.includes(email);
}

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename).getContent();
}

I also tried changing the manage deployments I’ve changed it into:

Execute as:
Me

Who has access:
Anyone with Google account

and changed the Session.getActiveUser into Session.getEffectiveUser but when the other users tried to access the web app even if they do not belong to AuthorizedUsers they can still access the web app.