creating a Blazor upload drag and drop button that links/binds to a ui table and displays the selected documents from selected popup?

enter image description here

what would the steps be to connect a a blazor drag and drop button to a ui table which displays selected documents onto the table? After selecting the document/multiple documents, whether it is pdf,png etc. It should display Name, LastName , Age , File Type and Date time uploaded

I created A class with Name, surname, Age, File Type and uploadedDateTime as well as a javascript file for dragging and dropping however when I select a file from the popup, the selected file has not showed up on the table

Ensuring Unique Code Usage in React Native and Expo Authentication

I’ve created a mobile app with react-native and expo for my studies. I’m trying to implement an authentication logic where the user has to enter an access code.

If the code complies with the verification rules, it will be stored in a mongodb database and allowed to log in to the app. It’s important to note that the code can only be used once.

I’ve tried all sorts of ways to do this logic, but without any success, I’m managing to use the code more than once, which I don’t want. Below is my backend and frontend code.

– server.js

require('dotenv').config();
const express = require('express');
const cors = require('cors'); // Importar cors
const { MongoClient } = require('mongodb');
const crypto = require('crypto');

const app = express();
const port = process.env.PORT || 3000;

app.use(cors()); // Usar cors
app.use(express.json());

const uri = process.env.MONGODB_URI;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

let db;
client.connect()
  .then(() => {
    db = client.db('pesagem');
    console.log('Connected to MongoDB');
  })
  .catch(err => console.error('Error connecting to MongoDB', err));

const validateCode = (code) => {
  const codeParts = code.split('-');
  if (codeParts.length !== 4) {
    console.log('Invalid code format');
    return { valid: false, message: 'Código inválido.' };
  }

  const [timestamp, random, userType, hash] = codeParts;
  const originalData = `${timestamp}-${random}-${userType}`;
  const generatedHash = crypto.createHash('sha256').update(originalData).digest('hex');

  console.log('Generated Hash:', generatedHash);

  if (hash !== generatedHash) {
    console.log('Invalid code: hash does not match');
    return { valid: false, message: 'Código inválido.' };
  }

  let userTypeText;
  switch (userType) {
    case '0':
      userTypeText = '5';
      break;
    default:
      console.log('Invalid userType');
      return { valid: false, message: 'Código inválido.' };
  }

  return { valid: true, userTypeText };
};

app.post('/check-code', async (req, res) => {
  const { code } = req.body;

  if (!code) {
    console.log('Código não fornecido.');
    return res.status(400).send({ error: 'Código não fornecido' });
  }

  console.log('Received code:', code);

  const validationResult = validateCode(code);
  if (!validationResult.valid) {
    console.log('Validation result:', validationResult);
    return res.status(400).send({ error: validationResult.message });
  }

  try {
    const codesCollection = db.collection('usedCodes');
    const existingCode = await codesCollection.findOne({ code });

    if (existingCode) {
      console.log(`Código ${code} já utilizado.`);
      return res.status(400).send({ error: 'Este código já foi utilizado.' });
    }

    await codesCollection.insertOne({ code });
    console.log(`Código ${code} inserido com sucesso.`);
    return res.status(200).send({ message: 'Código válido e armazenado.', userType: validationResult.userTypeText });
  } catch (error) {
    console.error('Erro ao verificar o código', error);
    return res.status(500).send({ error: 'Erro interno do servidor' });
  }
});

app.listen(port, () => {
  console.log(`Servidor rodando na porta ${port}`);
});

– Login.js

const Login = ({ loginDone }) => {
  const [code, setCode] = useState('');
  const [isAlertVisible, setIsAlertVisible] = useState(false);
  const [alertMessage, setAlertMessage] = useState('');

  const showAlert = (message) => {
    setAlertMessage(message);
    setIsAlertVisible(true);
  };

  const closeAlert = () => {
    setIsAlertVisible(false);
  };

  const checkCode = async () => {
    console.log('checkCode function called');
    try {
      if (!code) {
        console.log('No code provided');
        showAlert('Por favor, insira um código para verificar.');
        return;
      }

      const codeParts = code.split('-');
      if (codeParts.length !== 4) {
        console.log('Invalid code format');
        showAlert('Código inválido.');
        return;
      }

      const [timestamp, random, userType, hash] = codeParts;
      const originalData = `${timestamp}-${random}-${userType}`;
      const generatedHash = await Crypto.digestStringAsync(
        Crypto.CryptoDigestAlgorithm.SHA256,
        originalData
      );

      console.log('Generated Hash:', generatedHash);

      if (hash !== generatedHash) {
        console.log('Invalid code: hash does not match');
        showAlert('Código inválido.');
        return;
      }

      console.log('Sending code to API:', code);
      const response = await axios.post(`${API_URL}/check-code`, { code });

      if (response.data.error) {
        console.log('API returned an error:', response.data.error);
        showAlert(response.data.error);
        loginDone(false, 0);
      } else {
        console.log('Login successful, user type:', response.data.userType);
        loginDone(true, response.data.userType);
        setCode('');
      }
    } catch (error) {
      if (error.response) {
        console.log('Erro na resposta da API:', error.response.data);
        showAlert('Erro ao verificar o código: ' + error.response.data.error);
      } else if (error.request) {
        console.log('Erro na requisição:', error.request);
        showAlert('Erro na conexão com o servidor.');
      } else {
        console.log('Erro desconhecido:', error.message);
        showAlert('Erro ao verificar o código.');
      }
      loginDone(false, 0);
    }
  };

When submitting form, I get “Cannot Post /”

I am building a reverse proxy, in it, there is a form box. It is supposed to get user input, and check if it is:

  1. a url;
  2. a url without the https:// header, which it adds;
  3. or plain text, which is routed into a search engine.

Wen submitting the form, no matter what is in it, it returns “Cannot Post /” in a blank page. My index.html form is this.

<div class="search-container">
    <p>Join the <a href="https://discord.gg/3TTahctF">discord</a>!</p>
    <form id="fs" method="POST">
        <input id="is" class="main-search" placeholder="A World, Uncensored" type="text" />
    </form>
</div>

In my index.js, which is connected, this.

window.addEventListener('load', () => {
  navigator.serviceWorker.register('../sw.js?v=4', {
    scope: '/a/',
  })
})

const form = document.getElementById('fs')
const input = document.getElementById('is')

if (form && input) {
  form.addEventListener("submit", async event => {
    event.preventDefault();
    processUrl(input.value, "");
  });
}

function processUrl(value, path) {
  let url = value.trim()
  const engine = localStorage.getItem('engine')
  const searchUrl = engine ? engine : 'https://www.google.com/search?q='

  if (!isUrl(url)) {
    url = searchUrl + url
  } else if (!(url.startsWith('https://') || url.startsWith('http://'))) {
    url = 'https://' + url
  }

  sessionStorage.setItem('GoUrl', __uv$config.encodeUrl(url))
  const dy = localStorage.getItem('dy')

  if (path) {
    location.href = path
  } else if (dy === 'true') {
    window.location.href = '/a/q/' + __uv$config.encodeUrl(url)
  } else {
    window.location.href = '/a/' + __uv$config.encodeUrl(url)
  }
}

function isUrl(val = '') {
  if (/^http(s?):///.test(val) || (val.includes('.') && val.substr(0, 1) !== ' ')) return true
  return false
}

First, I tried changing the form’s method, which gave me a similar error. Then, after doing research online, I came to this link. Although similar, it is focused on an express error, while mine is basic javascript (client side).

How to access OneSignal web push notifications data in order to perform other actions

I’m trying to access OneSignal web push notification data to update other parts of my website. However, the on(‘notificationDisplay’) or on(‘notificationDismiss’) events are not being triggered. My website is served over HTTPS, so that shouldn’t be the issue. Here’s my current implementation:

<!DOCTYPE html>
<html>
<head>
  <script src="https://cdn.onesignal.com/sdks/OneSignalPageSDKES6.js?v=151606" async=""></script>
  <script>
    var onesignalAppId = "1234567890";
    var idWriter = "12345";
    var OneSignal = window.OneSignal || [];

    if (onesignalAppId) {
      OneSignal.push(function() {
        OneSignal.init({
          appId: onesignalAppId,
          notifyButton: { enable: true },
          logLevel: 'trace'  // Enable verbose logging
        });

        OneSignal.showNativePrompt();

        OneSignal.on('notificationDisplay', function(event) {
          console.log('OneSignal notification displayed:', event);
          alert(event);
        });

        OneSignal.on('notificationDismiss', function(event) {
          console.log('OneSignal notification dismissed:', event);
        });

        OneSignal.on('subscriptionChange', function(isSubscribed) {
          console.log('Subscription changed:', isSubscribed);
        });

        if (idWriter) {
          OneSignal.setExternalUserId(idWriter);
        }
      });
    }
  </script>
</head>
<body>
  Content
</body>
</html>

I’ve seen similar questions suggesting that these events only work on HTTPS sites, but my site is indeed HTTPS. What could be the problem?

Are there any common issues or additional configurations that I might be missing? Any help would be appreciated.

React Context.Provider returns undefined

I have a Context.Provider with a value
When I import it in the child component with useContext it returns undefined
I don’t see what I’m missing here

For context here is the folder structure

src
    slider
        edit.js
        index.js
    slide
        edit.js
        index.js

build
    slider
        index.js
    slide
        index.js

index.js

import { registerBlockType } from '@wordpress/blocks';
import './style.scss';

/**
 * Internal dependencies
 */
import Edit from './edit';
import save from './save';
import metadata from './block.json';

/**
 * Every block starts by registering a new block type definition.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-registration/
 */
registerBlockType( metadata.name, {
    /**
     * @see ./edit.js
     */
    edit: Edit,

    /**
     * @see ./save.js
     */
    save,
} );
import React, { createContext, useRef } from 'react'
import { useBlockProps, InnerBlocks } from '@wordpress/block-editor'

export const SlideContext = createContext()

export default function Edit() {
    const slideRefs = useRef([])

    const setSlideRef = (ref, index) => {
        slideRefs.current[index] = ref
        console.log('setSlideRef called with ref:', ref, 'and index:', index)
    }

    // some code omitted for brevity

    console.log('Rendering Slider component with context value:', { setSlideRef })

    const blockProps = useBlockProps()

    return (
        <SlideContext.Provider value={{ setSlideRef }}>
            <div {...blockProps}>
                <div className='splash-slider__wrapper'>
                    <div
                        className='splash-slider__track'
                    >
                        <InnerBlocks
                            allowedBlocks={['splash-blocks/slide']}
                            renderAppender={() => <InnerBlocks.ButtonBlockAppender />}
                            templateLock={false}
                        />
                    </div>
                </div>
            </div>
        </SlideContext.Provider>
    )
}

import { useBlockProps, InnerBlocks } from '@wordpress/block-editor'
import { useEffect, useRef, useContext } from '@wordpress/element' // Same as React
import { SlideContext } from '../slider/edit' // Import the context from the parent block

export default function Edit({ attributes, setAttributes, clientId }) {
    const blockProps = useBlockProps({
        className: 'splash-slider__slide'
    })
    const slideRef = useRef()

    const slideContext = useContext(SlideContext)
    console.log('slideContext:', slideContext) // logs: undefined
    const { setSlideRef } = slideContext || {}

    useEffect(() => {
        console.log('slideRef.current:', slideRef.current) // logs correctly
        if (setSlideRef && slideRef.current) {
            console.log('Setting slideRef with clientId:', clientId)

            setSlideRef(slideRef, clientId)
        }
    }, [setSlideRef, clientId])

    return (
        <div {...blockProps} ref={slideRef}>
            // InspectorControls and PanelBody omitted for brevity
            <InnerBlocks />
        </div>
    )
}

Troubleshoot deploying cloud functions error with typecasting in node modules

I’m building a reactjs pwa. trying to implement cloud functions in my project.
I’m trying to deploy firebase cloud functions but getting the same error despite trying a couple of things:

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:13:11 - error TS2304: Cannot find name 'AllowSharedBufferSource'.

13     data: AllowSharedBufferSource;
             ~~~~~~~~~~~~~~~~~~~~~~~

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:23:19 - error TS2304: Cannot find name 'AllowSharedBufferSource'.

23     description?: AllowSharedBufferSource | undefined;
                     ~~~~~~~~~~~~~~~~~~~~~~~

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:56:14 - error TS2304: Cannot find name 'AvcBitstreamFormat'.

56     format?: AvcBitstreamFormat | undefined;
                ~~~~~~~~~~~~~~~~~~

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:60:11 - error TS2304: Cannot find name 'AllowSharedBufferSource'.

60     data: AllowSharedBufferSource;
             ~~~~~~~~~~~~~~~~~~~~~~~

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:71:11 - error TS2304: Cannot find name 'AllowSharedBufferSource'.

71     data: AllowSharedBufferSource;
             ~~~~~~~~~~~~~~~~~~~~~~~

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:74:11 - error TS2552: Cannot find name 'EncodedVideoChunkType'. Did you mean 'EncodedVideoChunk'?

74     type: EncodedVideoChunkType;
             ~~~~~~~~~~~~~~~~~~~~~

  ../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:266:13
    266 declare var EncodedVideoChunk: {
                    ~~~~~~~~~~~~~~~~~
    'EncodedVideoChunk' is declared here.

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:119:19 - error TS2304: Cannot find name 'AllowSharedBufferSource'.

119     description?: AllowSharedBufferSource | undefined;
                      ~~~~~~~~~~~~~~~~~~~~~~~

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:137:13 - error TS2304: Cannot find name 'AlphaOption'.

137     alpha?: AlphaOption | undefined;
                ~~~~~~~~~~~

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:140:19 - error TS2304: Cannot find name 'VideoEncoderBitrateMode'.

140     bitrateMode?: VideoEncoderBitrateMode | undefined;
                      ~~~~~~~~~~~~~~~~~~~~~~~

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:147:19 - error TS2304: Cannot find name 'LatencyMode'.

147     latencyMode?: LatencyMode | undefined;
                      ~~~~~~~~~~~

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:173:13 - error TS2304: Cannot find name 'VideoPixelFormat'.

173     format: VideoPixelFormat;
                ~~~~~~~~~~~~~~~~

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:185:13 - error TS2304: Cannot find name 'AlphaOption'.

185     alpha?: AlphaOption | undefined;
                ~~~~~~~~~~~

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:203:25 - error TS2304: Cannot find name 'AllowSharedBufferSource'.

203     copyTo(destination: AllowSharedBufferSource, options: AudioDataCopyToOptions): void;
                            ~~~~~~~~~~~~~~~~~~~~~~~

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:214:21 - error TS2304: Cannot find name 'CodecState'.

214     readonly state: CodecState;
                        ~~~~~~~~~~

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:231:21 - error TS2304: Cannot find name 'CodecState'.

231     readonly state: CodecState;
                        ~~~~~~~~~~

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:250:25 - error TS2304: Cannot find name 'AllowSharedBufferSource'.

250     copyTo(destination: AllowSharedBufferSource): void;
                            ~~~~~~~~~~~~~~~~~~~~~~~

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:262:20 - error TS2304: Cannot find name 'EncodedVideoChunkType'.

262     readonly type: EncodedVideoChunkType;
                       ~~~~~~~~~~~~~~~~~~~~~

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:263:25 - error TS2304: Cannot find name 'AllowSharedBufferSource'.

263     copyTo(destination: AllowSharedBufferSource): void;
                            ~~~~~~~~~~~~~~~~~~~~~~~

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:329:21 - error TS2304: Cannot find name 'CodecState'.

329     readonly state: CodecState;
                        ~~~~~~~~~~

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:346:21 - error TS2304: Cannot find name 'CodecState'.

346     readonly state: CodecState;
                        ~~~~~~~~~~

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:368:22 - error TS2304: Cannot find name 'VideoPixelFormat'.

368     readonly format: VideoPixelFormat | null;
                         ~~~~~~~~~~~~~~~~

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:374:25 - error TS2304: Cannot find name 'AllowSharedBufferSource'.

374     copyTo(destination: AllowSharedBufferSource, options?: VideoFrameCopyToOptions): Promise<PlaneLayout[]>;
                            ~~~~~~~~~~~~~~~~~~~~~~~

../node_modules/@types/dom-webcodecs/webcodecs.generated.d.ts:380:15 - error TS2304: Cannot find name 'AllowSharedBufferSource'.

380     new(data: AllowSharedBufferSource, init: VideoFrameBufferInit): VideoFrame;
                  ~~~~~~~~~~~~~~~~~~~~~~~


Found 23 errors in the same file, starting at: ../node_modules/@types/dom-webcodecs/webcodecs.genera

I have tried:

  • updating packages
  • reinstalling webcodec/ types/dom-webcodecs (getting up to date)
  • Googling around

Don’t know what else to try.

PixiJS character animated sprite not updating when getting reassigned

I am trying to update an animated sprite object and i have instantiated them like this: characterMovement["walk_down"] = PIXI.AnimatedSprite.fromFrames(animations["walk_down/walk_down"]); characterMovement["walk_up"] = PIXI.AnimatedSprite.fromFrames(animations["walk_up/walk_up"]); characterMovement["walk_left"] = PIXI.AnimatedSprite.fromFrames(animations["walk_left/walk_left"]); characterMovement["walk_right"] = PIXI.AnimatedSprite.fromFrames(animations["walk_right/walk_right"]);

I then assign it like this:
character = characterMovement["walk_down"];

then I have some code that dependign on what key is pressed the animated sprite object should change like this: if (keys['87'] && character.y > 0) { character= characterMovement["walk_up"];

however nothing happens when i reassign it.

I have tried just reassigning the textures like this: character.textures = characterMovement["walk_up"].textures; and that works but doesnt cycle through the animations.

Peeking the contents of NextRequest.body in Next.js middleware

This is my middleware.js file for Next.js:

import { NextResponse }         from 'next/server';
import { createCsrfMiddleware } from '@edge-csrf/nextjs';

const csrfMiddleware = createCsrfMiddleware({
    secret  : process.env.CSRF_SECRET,
    cookie  : {
        secure   : process.env.NODE_ENV === 'production',
        sameSite : 'strict',
        httpOnly : true
    }
});

export const middleware = async (req) => {
    const path = req.nextUrl.pathname;
    if (req.method === 'POST' && path === '/api/whatever') {
        try {
            console.warn(`checking skip in ${path}...`);
            const decoder = new TextDecoder('utf-8');
            let wholeBody = decoder.decode(await req.arrayBuffer());
            const json = JSON.parse(wholeBody);
            if (json.action === 'skip') {
                console.warn(`skipped: '${wholeBody}'`);
                return NextResponse.next();
            }
            else {
                console.warn('skip ignored');
                return csrfMiddleware(req); // body is unusable
            }
        }
        catch (err) {
            console.warn(`skip check failed in ${path}: ${err.message}`);
            return new NextResponse('Internal Server Error', { status: 500 });
        }
    }
    return csrfMiddleware(req);
};

Notice two things:

  1. I am using @edge-csrf/nextjs to prevent CSRF, but that’s not important.
  2. I am trying to skip the CSRF middleware by inspecting the CONTENTS of the payload.
    Yes. I know this is a weird case, and usually it’s done by ignoring a whole API path. But I want to know if it’s possible to do it this way.

Having said that, there is an issue right there in the line with the comment.
Before reaching that part, the body has been ‘consumed’ by (I guess) req.arrayBuffer().
Hence it cannot be used again.

So I wonder if is it possible to read the body and rewind the thing (haha) or peeking into it in some way.

Thanks for your ideas/comments.

Cloudflare Pages & apiKeys

Heya I am encountering an issue trying to get the request for my static website that was deployed to Cloudflare Workers to function and giving me errors my script. The error in the console on the page is VM1507:1 Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

My file structure is:

-functions
--env.js
-Images
-Scripts
--gallery.js
-Styles
-index.html

The primary focus is env.js and gallery.js.

env.js:

async function onRequest(context) {
  const folderID = context.env.folderID;
  const apiKey = context.env.apiKey;

  const response = new Response(JSON.stringify({ folderID, apiKey }));
  response.headers.set("Content-Type", "application/json");

  return response;
}

gallery.js:

async function fetchImages() {
  try {
    const envResponse = await fetch("/functions/env");
    const { folderID, apiKey } = await envResponse.json();

    const imageDataResponse = await fetch(
      `https://www.googleapis.com/drive/v3/files?q=${folderID}+in+parents&key=${apiKey}&fields=files(id,name,mimeType,thumbnailLink,webContentLink)`
    );
    const imageData = await imageDataResponse.json();
    displayImages(imageData.files);
  } catch (error) {
    console.error("Error fetching env data:", error);
  }
}

function displayImages(files) {
  const gallery = document.getElementById("gallery");
  const slidesContainer = document.createElement("div");
  slidesContainer.id = "slides";
  gallery.appendChild(slidesContainer);

  files.forEach((file, index) => {
    if (file.mimeType.startsWith("image/")) {
      const img = document.createElement("img");
      img.src =
        file.thumbnailLink ||
        `https://drive.google.com/uc?export=view&id=${file.id}`;
      img.alt = file.name;
      img.classList.add("slide");
      if (index === 0) {
        img.classList.add("active");
      }
      slidesContainer.appendChild(img);
    }
  });
  addGalleryNavigation();
}

function addGalleryNavigation() {
  const slides = document.querySelectorAll(".slide");
  let currentIndex = 0;

  document.getElementById("nextBtn").addEventListener("click", () => {
    slides[currentIndex].classList.remove("active");
    currentIndex = (currentIndex + 1) % slides.length;
    slides[currentIndex].classList.add("active");
  });

  document.getElementById("prevBtn").addEventListener("click", () => {
    slides[currentIndex].classList.remove("active");
    currentIndex = (currentIndex - 1 + slides.length) % slides.length;
    slides[currentIndex].classList.add("active");
  });
}

fetchImages();

I have tried putting a try catch for error handling and still getting the same error, I have also substituted the envData by hard coding in my apiKey and folderId variables back.

Is there a way to copy/get responses directly from chrome browser with python?

I have a python code that uses selenium, I’m not expert with web development and I’m trying to get responses from some dropdowns that are cascading each other, when you select a value from one dropdown it retrieves a response with the values of the next dropdown. One of those is a date picker that contains available days in JSON format instead of going through the calendar, I can know which one is available by getting this JSON response, I found a feature in Google Chrome that allows you to get this information if you open the developer tools and go to the Network tab -> right-click to the file -> copy -> copy response, is there any way to do the same or use this feature with code using python and selenium or maybe pure JavaScript? Selenium allows you to run JavaScript commands

Please see what I’m trying to explain in the below picture with Google:

enter image description here

I have found some suggested solutions in this post:

Selenium – python. how to capture network traffic’s response

But not sure if there’s any other straight-forward solution as I mentioned directly from browser.

how to add value off input into table?

I have successfully added the custom taxonomy for employer tags to the employer table. However, I am currently unable to retrieve and save the values from the input field on the meta box. As of now, tags can only be added manually through the WordPress dashboard. I attempted the following code to resolve this issue, but it did not work as expected.
this is the input:

<input type="text" class="regular-text" name="tag" id="tag" value="" placeholder="tag1, tag2, tag3"'/>

function create_employer_custom_taxonomy() {    
    $labels = array(
        'name'              => _x('Employer Tags', 'taxonomy general name', 'textdomain'),
        'singular_name'     => _x('Employer Tag', 'taxonomy singular name', 'textdomain'),
        'search_items'      => __('Search Employer Tags', 'textdomain'),
        'all_items'         => __('All Employer Tags', 'textdomain'),
        'parent_item'       => __('Parent Employer Tag', 'textdomain'),
        'parent_item_colon' => __('Parent Employer Tag:', 'textdomain'),
        'edit_item'         => __('Edit Employer Tag', 'textdomain'),
        'update_item'       => __('Update Employer Tag', 'textdomain'),
        'add_new_item'      => __('Add New Employer Tag', 'textdomain'),
        'new_item_name'     => __('New Employer Tag Name', 'textdomain'),
        'menu_name'         => __('Employer Tags', 'textdomain'),
    );
    $args = array(
        'hierarchical'      => false,
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'update_count_callback' => '_update_post_term_count',
        'query_var'         => true,
        'rewrite'           => array('slug' => 'employer_tag'),
    );
    register_taxonomy('employer_tag', 'employer', $args);
}
add_action('init', 'create_employer_custom_taxonomy');

function add_employer_tags_meta_box() {
    add_meta_box(
        'employer_tags_meta_box',
        'Employer Tags',
        'employer_tags_meta_box_callback',
        'employer', // Post type
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'add_employer_tags_meta_box');

function employer_tags_meta_box_callback($post) {
    wp_nonce_field('save_employer_tags_meta_box_data', 'employer_tags_meta_box_nonce');
    $tags = wp_get_post_terms($post->ID, 'employer_tag', array('fields' => 'names'));
    $tags_string = implode(', ', $tags); // Convert array to comma-separated string
    echo '<div class="cmb-td">';
    echo '<input type="text" class="regular-text" name="tag" id="tag" value="' . esc_attr($tags_string) . '" placeholder="Tag1, Tag2, Tag3" />';
    echo '</div>';
}


function save_employer_tags_meta_box_data($post_id) {
    if (!isset($_POST['employer_tags_meta_box_nonce'])) {
        return;
    }
    if (!wp_verify_nonce($_POST['employer_tags_meta_box_nonce'], 'save_employer_tags_meta_box_data')) {
        return;
    }
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }

    if (isset($_POST['tag'])) {
        $tags = sanitize_text_field($_POST['tag']);
        // Split tags by comma and trim whitespace
        $tags_array = array_map('trim', explode(',', $tags));
        // Save tags to the custom taxonomy
        if (!empty($tags_array)) {
             foreach ($tags_array as $tag) {
                if (!term_exists($tag, 'employer_tag')) {
                    wp_insert_term($tag, 'employer_tag');
                }
            }
            wp_set_post_terms($post_id, $tags_array, 'employer_tag', false);
        } 
    }
}
add_action('save_post', 'save_employer_tags_meta_box_data');

function display_employer_tags() {
    global $post;
    $tags = wp_get_post_terms($post->ID, 'employer_tag');
    if (!empty($tags)) {
        echo '<div class="employer-tags">';
        echo '<h3>Tags:</h3>';
        echo '<ul>';
        foreach ($tags as $tag) {
            echo '<li>' . esc_html($tag->name) . '</li>';
        }
        echo '</ul>';
        echo '</div>';
    }
}
add_action('freeio_single_employer_after', 'display_employer_tags');

Vue Child component loses reactivity to retrieved pinia/vueFire object

I am trying to load an item into a child component so I can edit the values. I am passing an itemId from the parent to the child as a prop and in the child I call a function store.itemForId(id) to retrieve the itemData from a vueFire/firstore collection. I can retrieve the item document in the child but it loses reactivity. If the firestore Document gets updated externally, the collection in the pinia store and the data in the parent gets updated but the item retrieved in the child does not.

However, if I use the same function in the parent and instead pass the item to the child, the reactivity stays.
This isn’t a solution because I will eventually need to be able to edit the item, but it makes me think the problem lies in the child somehow.

I’ve got a pinia store that gets a projectItems Collection and a projectInfo Document.

projectInfo.itemOrder gives the display order for the items.

// projectStore.js
const projectInfo = useDocument(() => doc(db, projectPath))
const { data:projectItems, promise:itemsPromise } = useCollection(() => collection(db, itemsPath))


function itemForId(id) {
  return projectItems.value.find((item) => item.id === id)
}

MyParent.vue

<script setup>
  import { useProjectStore } from 'stores/projectStore'

  const projectStore = useProjectStore()
  const { projectInfo, projectItems } = storeToRefs(projectStore)
</setup>
<template>

  <div>Child gets Id</div> <!-- not reactive -->
  <template v-for="itemId in projectInfo.itemOrder" :key="itemId">
    <IdChild :itemId="itemId" /> 
  </template>

  <div>Child gets Item</div> <!-- reactive -->
  <template v-for="itemId in projectInfo.itemOrder" :key="itemId">
    <ItemChild :item="projectStore.itemForId(itemId)" /> 
  </template>

  <div>Raw ItemData</div> <!-- reactive -->
  <div>{{ projectItems }}</div> 
</template>

IdChild.vue is not reactive

<script setup>
  import { useProjectStore } from 'stores/projectStore'
  
  const props = defineProps({ itemId: String })

  const projectStore = useProjectStore()
  const { projectItems } = storeToRefs(projectStore)

  // this seems to be where reactivity is lost. Tried with both ref and without.
  // console.log(item) shows it as a RefImpl / Proxy so it seems correct
  const item = ref(projectStore.itemForId(props.itemId))


</setup>
<template>

  <div>{{ item.name }}</div> <!-- not reactive -->
  
  <!-- this is reactive but seems wrong to have to do for every value -->
  <div>{{ projectStore.itemForId(itemId).name }}</div> 

  <div>Raw ItemData</div> <!-- for troubleshooting... but reactive too -->
  <div>{{ projectItems }}</div> 
</template>

ItemChild.vue – To troubleshoot I also made this which is reactive but since the item is passed as a prop it’s not editable.

<script setup>
  import { useProjectStore } from 'stores/projectStore'
  
  const props = defineProps({ item: Object })

</setup>
<template>

  <div>{{ item.name }}</div> <!-- reactive -->
  
</template>

How do I make a ref to the item in my child reactive?

Or is there something I am not understanding with how the reactivity works?

Issue with loading js library – unpkg.com v cdnjs.cloudflare.com – inside DOMContentLoaded event

I was having an issue that I was not able to use .insertString("Hello") method of Trix editor. I was 100% following instructions of official documentation https://github.com/basecamp/trix#inserting-and-deleting-text

I found out that the issue is the location of Trix library I was using.

If Trix is loaded from https://cdnjs.cloudflare.com everything works fine but unpkg.com

Could someone please explain how come such issue is happening of the code is inside DOMContentLoaded event? I thought that load event would solve it but the javascript code inserting text is not working with load event at all. Working jsFiddle

// document.addEventListener("load", function(event) {
 document.addEventListener("DOMContentLoaded", function(event) {
    // Your code to run since DOM is loaded and ready
     
     var element2 = document.querySelector("trix-editor")
     element2.editor  // is a Trix.Editor instance
     element2.editor.insertString("Hello2")
     
    });`enter code here`

React Native app not building due to mismatch between js and native codes and other potential issues

im stuck during 1 week now to simply build my react native app for my first project in a company, basically for android it said it has a mismatch between react native and native code versions, 0.61.3 and 0.64.4 basically, it said I could rebuild the native code to update it, i tried to run npx react-native run-ios and run-android but none of them worked because they didnt recognized a command I had to install, it was pod, i should do pod install, but to do this it requires an ubuntu password which i dont have because i use vs code inside the company’s server, my pc uses windows 11 but this virtual machine uses ubuntu… so i tried to forcelly change react native version to 0.64.4 and now the log error is not even showing in the app anymore, app is not building.

It says ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect.
This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.
ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect.
This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.

probably because of the forced change but I dont know I just dont want to be kicked off in 1 week of my first project for an international client

I tried to npx react-native run-ios and run-android, i tried to install brew, pod, cocoapods, all of them required sudo command which requires a password which i dont and cannot have access.. My tech lead could not help me, the pm just wants the tasks to be done.. the other rn dev of the team couldnt help… so im asking you guys

im learning can someone explain me why this are happen in my code, many thanks in advance

setInterval(function(){
    let mostra = document.getElementById("mostrar");
    let contagem = ["5","4","3","2","1","..."];
    let ic = 0;
    let conta = contagem[ic];
    while(conta <= contagem.length){
        
        mostra.textContent = `algum texto  ${conta++}`;
    }
}, 1000);

and this not works and i try …

setInterval(function(){
    let mostra = document.getElementById("mostrar");
    let contagem = ["5","4","3","2","1","..."];
    for(let ic = 0; ic <= contagem.length; ic++){
        let conta = contagem[ic];
        mostra.textContent = `algum texto  ${conta++}`;
    }
}, 1000);

both failed im trying to redirect a user to home page and do 5, 4, 3, 2, 1, … and homepage

many thanks

someone to help me and explain what im doing wrong