React: how to make sure content is loaded and has scrollHeight and client height

I have the next code – useMemo calculates if container is ready, but in fact when container appears it returns false, is there any way to do it?

  const containerReady = useMemo(() => {
    const scrollHeight = messagesContainer.current?.scrollHeight;
    const clientHeight = messagesContainer.current?.clientHeight;

    if (!scrollHeight || !clientHeight) return false;

    return true;
  }, [
    messagesContainer.current?.scrollHeight,
    messagesContainer.current?.clientHeight,
  ]);

  console.log("Container ready:", containerReady);

Monitoring iOS safari crash: This webpage was reloaded because a problem occurred

I have problem with mobile safari in my react application. When user clicks on the button X I run memory-heavy-3d-component (three.js-based) and safari crashes with This webpage was reloaded because a problem occurred.

I’d like to understand how can I track these crashes for both 1) understanding how big is the issue and 2) monitoring occurrences while I fix it.

I thought about “hacky” way:

  1. store timestamp into localstorage when user clicks the button X
  2. on every app load check stored timestamp and if it is within the 5-10(?) seconds range from now – assume the app was crashed and trigger NewRelic monitoring event.

But are there any more native ways to track those crashes?

Shopify parameter passing from frontend to the order dashboard

I have a question. Im tryin to add the GET param to orders in shopify, pls check my steps, may be you could suggest something useful for me.
I added a parameter to the theme code through the template editor, but I noticed that the additional information was added only once, this is the place at dashboard at shopify where my data presented. I’ve run multiple tests, so why might this happen?

I’m confused about how it’s possible that the first attempt was successful while the rest failed.

Let me explain the idea I’m following. I have an additional parameter that gets passed as a URL GET parameter when a user visits the Shopify store. I wrote a script to store it in cookies and localStorage. The second script adds this parameter to the cart. I had one positive test where I found my parameter in the order in the admin panel, but the remaining three tests failed.

I placed the script in theme.liquid before the closing head tag.

It should work on every page since users can enter on any page, I mean the idea of getting the GET param. That’s why I tried to parse the parameter every time.

The second script adds the additional notes parameter to the cart once it exists, Im seeking for the form cart.

Finally, I want to receive a webhook or get orders data via the API. I prefer to receive a webhook, but there are too many parameters in the JSON, but this isn’t a question for now =)

<script>
// admitad
function setCookie(name, value) { 
  var days = 90; 
  var date = new Date();
  date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
  var expires = "; expires=" + date.toUTCString();
  document.cookie = name + "=" + (value || "") + expires + "; path=/“;
}

// get admitad_uid
if (window.location.search.indexOf('admitad_uid=') !== -1 || window.location.search.indexOf('tagtag_uid=') !== -1) {
  var params = new URLSearchParams(window.location.search);
  var uid = params.get('admitad_uid') || params.get('tagtag_uid’);
  if (uid) {
    // cookie
    setCookie('admitad_uid', uid);

    // localStorage
    localStorage.setItem('admitad_uid', uid);

    // save indexedDB
    var request = indexedDB.open("AdmitadDB", 1);
    request.onupgradeneeded = function(event) {
      var db = event.target.result;
      db.createObjectStore("uids", { autoIncrement: true });
    };
    request.onsuccess = function(event) {
      var db = event.target.result;
      var transaction = db.transaction(["uids"], "readwrite”);
      var store = transaction.objectStore("uids”);
      store.put(uid);
    };
  }
}
</script>
    <script>
document.addEventListener('DOMContentLoaded', function() {
  var uid = localStorage.getItem('admitad_uid') ||
            document.cookie.split('; ').find(row => row.startsWith('admitad_uid=')).split('=')[1];

  if (uid) {
    var form = document.querySelector('form[action="/cart"]’);
    if (form) {
      var input = document.createElement('input’);
      input.type = ‘hidden’;
      input.name = 'attributes[admitad_uid]’;
      input.value = uid;
      form.appendChild(input);
    }
  }
});
</script>[enter image description here][1]

1st order screenshot

2nd order screenshot

Get key value of jason Object with javascript

I have a json file with the following object:

{
  "month": "April",
  "events" : [
      "event 1",
      "event 2"     
   ] ,

"event 1": [
          "1.3",
          "2.3",
          "3.3",
          "4.3"
 ],
"event 2": [
  "7.3",
  "16.3"
 ]
}

I’d like to get the key of the Object for further transactions.

let datesOfEvents = [];
var jSObject = getData().then((a) =>{   

            for (let i = 0; i<a.length;i++){
                
                    if(typeof a[i].events !== 'undefined'){
                         
                        for (let key in a[i] ){
                                        
                            if (key == "event1"){
                                    datesOfEvents = a[i].key;   

                            }
                        }   

                   }
                }
             })

As the key value, I’m asking for in the if statement is a String, I cannot call the other values this way a[i].key. when I call them individually, like this:

datesOfEvents = a[i].event1; 

it works fine. My question is: what type do I have to query in the if statement to get the values of event1?

Loading MDX Files From public Directory In NUXT (production)

I Am Currently Trying to load mdx files from my nuxt projects public/docs folder my approch currently is as follows

async function loadMDX(componentPath) {
  try {

    const { public: { docsBasePath } } = useRuntimeConfig();

    console.log("Receved from nuxt: ", docsBasePath)

    // 1) Fetch the raw text so vfile-matter can parse it
    const res = await fetch(`/docs/${componentPath}`);
    const text = await res.text();

    // 2) Parse frontmatter from that text
    const file = new VFile({ value: text });
    matter(file);
    docsStates.value.selectedDocMatter = file.data.matter

    // 3) Now import the compiled MDX module (for rendering)
    const module = await import(`${docsBasePath}/${componentPath}`);
    mdxContent.value = wrapWithProvider(module.default);
  } catch (error) {
    console.error(error);
    mdxContent.value = null;
  }
}

the docsBasePath is from a .env or .env.production based on the enviroment and is as follows

DOCS_BASE_PATH=../../public/docs
// for developement
DOCS_BASE_PATH=/docs
//for production

in development loading this mdx files works perfectly but in production when deploying to vercel i simply get this error

Error:
TypeError: Failed to fetch dynamically imported module: https://vdocs-brown.vercel.app/docs/@v1.0.0/Custom%20Components/Components.mdx

why is my nuxt app not finding it especially since its listed under my vercel static served files with this path
My Mdx Listed On My Vercel Static files list

PHP MYQSL single insert statement to enter either NULL, or time as datetime value when INSERT statement uses variable?

Apologies up front: Self taught so sometimes I miss something really basic…

I have a JS application where users can enter a time in a form and can revisit the form and edit the time later. The entry is sent to a MYSQL DB using PHP and stored in a TIME-type column. There will be cases where a user will need to enter midnight, and other cases where a user will need to intentionally leave the time blank (so it cannot display as midnight), so it is important that the time display as “-:–” in the form’s input field if it has yet to be entered, but as “12:00” if the user actually intends for the entry to be midnight. As long as the value stores in the DB as NULL it works fine.

The problem is that if I simply allow the value to pass from JS to PHP and then insert as the variable ‘$TIME_ENTRY’ when sending from PHP, a ‘null’ from js is interpreted as ’12:00′ on insert (Seems to be driven by the fact of single quotes around the variable may be causing it to read as 0?).

My current workaround is simply to test for null and have two separate insert statements:

if null{ "INSERT INTO `TBL` (`TIMECOLUMN`) VALUES (NULL)"}
else { "INSERT INTO `TBL` (`TIMECOLUMN`) VALUES ('$TIME_ENTRY')"

but I have to believe it can be done in a single statement. Can anyone help with this?

FROM JS:

var t = $("#time_entry_field").val();
var request = $.ajax({
    url: "PHPFile.php",
    type: "POST",
    async: true,
    data: "Time=" + t,
    success: function(){
         ...etc
    }
})

IN “PHPFile.php”:

$TIME_ENTRY = $_POST['Time'];
$conn->query("INSERT INTO `TBL` (`TIMECOLUMN`) VALUES ('$TIME_ENTRY')");

The above will store the value as ’12:00:00′ in my DB on receiving an empty string from $(“#time_entry_field”).val().

However:

$TIME_ENTRY = $_POST['Time'];
$conn->query("INSERT INTO `TBL` (`TIMECOLUMN`) VALUES (NULL)");

works as expected and stores the value as NULL.

Is there some simple way to use a single insert statement without getting hungup on an empty string from JS reading as a 0 in php? I have to do a lot of different versions of this so it seems super wasteful to write a million if statements…

Smile2Emoji with the word “constructor” reactJs

I would like to explain my problem of the day

it’s quite simple to understand, I use a react package called smile2emoji,

when I

const text = checkText("constructor");
console.log("text", text);

it turns me around

function Object() { [native code] }

while I would like that to return me

"constructor"

if you have any ideas, thank you

or if you have another package more practical to use, i am interested too

Neff

How to play a notification sound in a Chrome extension when minimized?

I am creating a task manager extension. I managed to make notifications work when the task timer ends. The popup appears, and the notification sound plays, but if the extension is minimized, I cannot play the sound. Could I modify it in some way to avoid using offscreen documents?

background.js

let audioContext;
let audioBuffer;

// Initialize the audio when the background is loaded
async function initAudio() {
  try {
    audioContext = new (AudioContext || webkitAudioContext)();
    const response = await fetch(chrome.runtime.getURL('alert.mp3'));
    const arrayBuffer = await response.arrayBuffer();
    audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
  } catch (error) {
    console.error('Error initializing the audio:', error);
  }
}

// Play the sound
function playSound() {
  if (audioContext && audioBuffer) {
    const source = audioContext.createBufferSource();
    source.buffer = audioBuffer;
    source.connect(audioContext.destination);
    source.start(0);
  } else {
    console.warn('The audio was not initialized correctly.');
  }
}

// Listen for messages to play the sound
chrome.runtime.onMessage.addListener((message) => {
  if (message.type === 'playAlertSound') {
    playSound();
  }
});

// Handle alarms and notifications
chrome.alarms.onAlarm.addListener((alarm) => {
  chrome.notifications.create({
    type: 'basic',
    iconUrl: 'icon.png',
    title: 'Task Reminder!',
    message: `It’s time to complete the task: ${alarm.name}`,
    priority: 2,
  });
  playSound(); // Play the sound when an alarm is triggered
});

// Initialize the audio when the background is loaded
initAudio();

**popup.js
**

document.addEventListener('DOMContentLoaded', () => {
  let tasks = JSON.parse(localStorage.getItem('tasks')) || [];
  let editingTask = null;

  const addTaskForm = document.getElementById('add-task-form');
  const formIcon = document.getElementById('form-icon');
  const searchInput = document.getElementById('search-input');
  const taskList = document.getElementById('task-list');

  let audioContext;
  let audioBuffer;

  // Initialize the audio context and load the audio file
  async function initAudio() {
    try {
      audioContext = new (window.AudioContext || window.webkitAudioContext)();
      const response = await fetch(chrome.runtime.getURL('alert.mp3'));
      const arrayBuffer = await response.arrayBuffer();
      audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
    } catch (error) {
      console.error('Error initializing the audio:', error);
    }
  }

  // Play the alert sound
  function playSound() {
    if (audioBuffer && audioContext) {
      const source = audioContext.createBufferSource();
      source.buffer = audioBuffer;
      source.connect(audioContext.destination);
      source.start(0);
    } else {
      console.warn('Audio not initialized correctly.');
    }
  }

  // Listen for messages from background.js to play the sound
  chrome.runtime.onMessage.addListener((message) => {
    if (message.type === 'playSound') { // Make sure the type matches with background.js
      playSound();
    }
  });

  // Initialize the audio when the popup is loaded
  initAudio();
});

In the manifest, I have also declared the permissions, resources, and background.

**manifest.json
**

"permissions": [
    "storage",
    "alarms",
    "notifications"
  ],
  "web_accessible_resources": [
    {
      "resources": ["alert.mp3"],
      "matches": ["<all_urls>"]
    }
  ],
  "background": {
    "service_worker": "background.js"
  },

Modify the popup.js to include the play function.
Send a message from the background to the popup to trigger the sound.

The button I wrote in VueJS remains disabled

I wrote a voice command application for VUEJS, but once I press the talk button, it does not work again, I need to refresh the page, how can I solve this problem?

My Code;

    <div class="input">
      <button
        class="talk"
        :disabled="isRecording"
        @click="startListening"
      >
        <i class="fas fa-microphone-alt" />
      </button>
      <h1
        class="content"
        @click="startListening"
      >
        Konuş
      </h1>
    </div>

I tried this for a solution

    stopRecognition() {
      const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)()

      recognition.stop() // Stop speech recognition
      this.isRecording = false // Set recording status to false
    },

I tried to write the above function and call it with this.sasad but still can’t press the button for the 2nd time

FlatList re-render causing unwanted navigation when property update triggered by useState change

I’ve got a FlatList that takes a property called sections as it’s data property. Sections is computed when a useState, in it’s dependency array, changes after the user has entered or changed some data in a TextInput.

The FlatList and sections are in the same source file, the TextInput is in another, and the useState is in another. The useState is imported into both source files containing the FlatList and TextInput.

When I type in the TextInput field it unwantingly auto navigates to the screen with the FlatList. I’ve replaced setBleDevices in the setCloudID method with setTestValue(id). I can then type in the TextInput field and it doesn’t navigate away from that screen, so I’m pretty certain it’s setBleDevices that’s causing the unwanted navigation.

I’ve tried using bleDevices[bleDevice?.id] in the sections dependency array, so that it only triggers when the desired bleDevice has changes rather than the whole bleDevices state. I’ve also tried wrapping the sections method in a useFocusEffect, so that it’s only computed when the screen with the FlatList is visible to the user, and not while they’re in the screen with the TextInput field.

const cloudID = (() => {
    switch (settingsType) {
        case "Temperature":
            return bleDevices[bleDevice.id]?.sections?.Temperature?.cloud_id || "";
        case "Humidity":
            return bleDevices[bleDevice.id]?.sections?.Humidity?.cloud_id || "";
        case "Panic":
            return bleDevices[bleDevice.id]?.sections?.Panic?.cloud_id || "";
        default:
            return "";
    }
})();
        
const setCloudID = (id) => {
    setBleDevices((prevBleDevices) => {
        const updatedBleDevices = { ...prevBleDevices };
        updatedBleDevices[bleDevice.id] = {
            ...updatedBleDevices[bleDevice.id],
            bleDeviceAddress: bleDevice.id,
            sections: {
                ...updatedBleDevices[bleDevice.id]?.sections,
                [settingsType]: {
                    ...updatedBleDevices[bleDevice.id]?.sections?.[settingsType],
                    cloud_id: id,
            }
            }
        };
        return updatedBleDevices;
    });
};

const inputsConfig = [
    {
        value: cloudID,
        setValue: setCloudID,
        placeholder: `Cloud ${settingsType} ID - e.g. 22`,
        validationError: cloudIDError,
        setValidationError: setCloudIDError,
        validationFunction: isIDString,
        errorMessage: "Please use only whole numbers 0 to 9",
        keyboardType: "number-pad",
    },
    {
        value: localID,
        setValue: setLocalID,
        placeholder: `Local ${settingsType} ID - e.g. 10`,
        validationError: localIDError,
        setValidationError: setLocalIDError,
        validationFunction: isIDString,
        errorMessage: "Please use only whole numbers 0 to 9",
        keyboardType: "number-pad",
    }
];

{inputsConfig.map((input, index) => (
    <View key={index}>
        <TextInput
            style={[
                styles.textInput,
                input.validationFunction(input.value)
                    ? { borderColor: theme.text }
                    : { borderColor: Colors.danger },
                      { color: theme.text },
            ]}
            ref={(el) => (inputRefs.current[index] = el)}
            returnKeyType={index < inputsConfig.length - 1 ? "next" : "done"}
            onSubmitEditing={() => {
                if (index < inputsConfig.length - 1) {
                    inputRefs.current[index + 1].focus();
                } else if (canSave()) {
                    syncWithHub();
                }
            }}
            value={input.value}
            onChangeText={input.setValue}
            placeholder={input.placeholder}
            placeholderTextColor={Colors.darkGray}
            keyboardType={input.keyboardType}
        />
        <Text
            style={[
                styles.errorText,
                { marginTop: -15, marginBottom: 10 }
            ]}
        >
            {input.validationError}
        </Text>
    </View>
))}
import { useDevice } from "../../Context/DeviceContext.js";

const {
    hubDevice,
    bleDevice,
    setBleDevices,
    bleDevices
} = useDevice();

const sections = useMemo(() => {
   const device = bleDevices[bleDevice?.id];
   return BleSections({ device });
}, [bleDevice?.id, bleDevices]);

<FlatList
    data={sections}
    renderItem={({ item }) => (
        <BleSectionRender title={item.title} data={item.data} />
    )}
    keyExtractor={(item, index) => index.toString()}
    contentContainerStyle={ScanStyle.content}
/>

Use Font Awsome icon in Javascript [duplicate]

I have a toggle button for dark/light mode on my site (under construction). I would like to replace the words ‘light on’ and ‘light off’ (3rd line) with two Font Awesome icons (‘fa-solid fa-sun’ and ‘fa-solid fa-moon’ respectively).

  function updateButton({ buttonEl, isDark }) {
    const ariaCta = isDark ? "Change to light theme" : "Change to dark theme";
    const buttonCta = isDark ? "light on" : "light off";
    buttonEl.setAttribute("aria-label", ariaCta);
    buttonEl.innerText = buttonCta;
  }

The icons refuse to show up. (This snippet is part of a larger script to determine or set the dark/light mode. The script in itself works fine.)

I know how to use the FA-icons in html and css context, the library is already loaded on the site through FA’s wp-plugin, and icons show just fine when implemented in html – but I can’t get it to work in this js-script. My knowledge of js is limited, so I’m having a hard time pinpointing the reason.

Is there anyone that perhaps could suggest how to go about this?

Edit:

The question was instantly closed after posting, and a duplicate answer was suggested. I looked at that, and tried inserting the FA tag in the way suggested.

  function updateButton({ buttonEl, isDark }) {
    const ariaCta = isDark ? "Change to light theme" : "Change to dark theme";
    const buttonCta = isDark ? "<i class="fa-solid fa-sun"></i>" : "<i class="fa-solid fa-moon"></i>";
    buttonEl.setAttribute("aria-label", ariaCta);
    buttonEl.innerText = buttonCta;
  }

I had already tried this method before, and does not work, the icons do not show up.
I really would appreciate it if the question would be left open, so that people would actually get a change to answer, and I get a change to react to them. My knowledge on this matter is limited, I tried the ways that I know and that I found during a day of searching, without succes. This is why I turned to this forum, as suggested on the Font Awesome page.

How to show desktop version of website and mobile version of website automatically when the user open the website from different kind of devices? [duplicate]

To be more clear, when a visitor visit through mobile then it should redirect the visitor to the mobile version of my website ( m.site.com ) and if through desktop then redirect to the desktop version of website ( site.com ). So How can I do that? Any advice from you would be appreciated.

My website is written in php code.

How do i change height of childblocks in jqwidgets treemaps

{
                label: '.',
                value: 0.05,
                parent: 'City',
                color: '#fff',
                data: { description: "", title: "Road Side" }
            },

here can pass height and width of childblocks

$('#treemap').jqxTreeMap({
                width: 900,
                height: 200,
                source: data,
                colorRange: 50,
                layout: 'vertical',
                renderCallbacks: {
                    '*': function (element, value) {
                        if (value.data) {
                            element.jqxTooltip({
                                content: '<div><div style="font-weight: bold; max-width: 200px; font-family: verdana; font-size: 13px;">' + value.data.title + '</div><div style="width: 200px; font-family: verdana; font-size: 12px;">' + value.data.description + '</div></div>',
                                position: 'mouse',
                                autoHideDelay: 6000,
                                theme: theme
                            });
                        } else if (value.data === undefined) {
                            element.css({
                                backgroundColor: '#fff',
                                border: '1px solid #555'
                            });
                        }
                    }
                }
            });
        });

i want to display childblocks fix height and width where data has been passed from json

code”:4,”StatusCode”:400,”message”:”WS failed with code: 4 and reason: invalid auth message format”,”isWSFailure”:false

I used Next.js for my frontend.

I separate the token for user login authentication. I generate another token with the secret key provided by Stream.io provider to access the live stream. I’m not sure if my way of implementation was the right thing to do as it is causing an error the way I integrate the generation of token to access the broadcast.

  1. The user logs in to the dashboard (with authenticated token).
  2. When the user navigates to the stream page, it calls the backend to generate another token to authenticate the user to access Stream for broadcast. But an error occurs:

[client]: Failed to connect Error: {“code”:4,”StatusCode”:400,”message”:”WS failed with code: 4 and reason: invalid auth message format”,”isWSFailure”:false}
at StableWSConnection.connect (connection.ts:139:17)

I used Stream.io sdk provider for the streaming feature. It’s my first time here, I hope I clearly delivered my issue. Thank you so much in advance.

This is my frontend code– stream page

 const Stream: React.FC = () => {
  const apiKey = "thisIsTheApiKeyy";
  const callId = "thiscallid";
  const [client, setClient] = useState<StreamVideoClient | null>(null);
  const [call, setCall] = useState<any | null>(null);

  useEffect(() => {
    const initializeStream = async () => {
      try {
    
        const userData = await fetchUserData();
        console.log("User Data:", userData);
  
     
        const userId = userData?.user_id;
        console.log("User ID:", userId);
  
        if (userId) {
     
          const response = await instance.post('/api/generate-token', { userId });
  
          console.log("STREAM TOKEN response: ", response);
  
          const streamToken = response.data.token;
  

          const streamClient = StreamVideoClient.getOrCreateInstance({
            apiKey: apiKey,
            user: { id: userId, name: "ML LIVE" },
            token: streamToken,
          });
  
          setClient(streamClient);
          const streamCall = streamClient.call("livestream", callId);
          streamCall.join({ create: true });
          setCall(streamCall);
        } else {
          console.error("User ID not found");
        }
      } catch (error) {
        console.error("Error initializing Stream:", error);
      }
    };
  
    initializeStream();
  }, []);
  
  

  if (!client || !call) {
    return <div>Loading...</div>; 
  }

  return (
    <StreamVideo client={client}>
      <StreamCall call={call}>
      <LivestreamView call={call} />
      </StreamCall>
    </StreamVideo>
  );
}

export default Stream;

Below is the backend code using express
backend-generate the stream token

router.post('/generate-token', (req, res) => {
  const { userId } = req.body;

  if (!userId) {
    return res.status(400).json({ error: 'User ID is required' });
  }

  try {
    const token = jwt.sign({ user_id: userId }, process.env.STREAM_API_SECRET, {
      algorithm: 'HS256',
    });

    res.json({ token });
  } catch (error) {
    console.error('Error generating token:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});