how to separate languages from currencies using vu-i18n

I’m trying to let the user have the ability to change the display language and currency independently, I’m using the Vue-I18n plugin on Vue3+Vite project. The project needs to support more than 20 languages and more than 25 currencies, until now I couldn’t find a clear way to do it, the closest thing I could think of is to make multiple number formatting rules for each language-currency combination like so :

localize/currencies.js

export default {
  'en-US': {
    currency: {
      style: "currency",
      currency: "USD",
      ...
    }
  },
  'ru-US': {
    currency: {
      style: "currency",
      currency: "USD",
      ...
    }
  }
}

then add it as numberFormats option of Vue-I18n’s createI18n function like so

localize/index.js

import numberFormats from "./currencies.js";

export default createI18n({
  ...
  numberFormats,
  ...
})

this would work however this means that I’ve got to make about 500 entries for each language-currency(country) combination, which makes me smile just by thinking of it :). also this won’t work if I wanted to use two letter identifiers like en instead of en-US, using a two letter approach makes more sense for my use case as browsers only show the languages preference and related country from navigator.language property, so I doubt that I’ll see something like ar-CA Arabic language with Canadian Dollar.

so is there any recommended way? I’m new to I18n and the internationalization problems in general it’s my first time.

Check if an array has an object with a certain property

I have an array of objects:

const arr = [
{ puzzle: [1,3,4,8,0,2,7,6,5], children: [] }, 
{ puzzle: [1,2,3,4,5,6,7,8] }
]

And I have an object:

const element = { puzzle: [1,3,4,8,0,2,7,6,5], children: ["1"]}

Im trying to see if element.puzzle is a value for a property of any of the objects in the array – in this particular example
element.puzzle === arr[0].puzzle, but a few methods I tried give the wrong result, so obviously I`m wrong…

array.some() method gives wrong result

arr.some(item => item.puzzle === element.puzzle) // gives false
arr.find(item=>item.puzzle === element.puzzle) //gives undefined

Trying to change from a select array to a find array

First time posting, not sure what is needed. Want these locations as results within a search rather than a dropdown select.

$location_select = array(
    'Elm Park' => 'Elm Park',
    'Rainham' => 'Rainham',
    'Dagenham' => 'Dagenham',
    'Romford' => 'Romford',
    'Hornchurch' => 'Hornchurch',
    'Upminster' => 'Upminster',
    'South Ockendon' => 'South Ockendon',
    'Purfleet' => 'Purfleet',
    'Grays' => 'Grays',
    'Stanford-Le-Hope' => 'Stanford-Le-Hope',
    'Basildon' => 'Basildon',
    'Pitsea' => 'Pitsea',
);

Here is the code they already have.

<form name="ph_property_search" class="ph_property_search px-2" action="<?php echo get_post_type_archive_link( 'property' ); ?>" method="get" role="form">

    <div class="row mx-auto">

        <div class="col-12 col-md-2 d-flex px-0">

            <div class="form-group my-auto w-100 accent-right py-2 py-md-0">
                <select id="location" name="address_keyword" class="location form-control area">
                <option value="0" selected disabled>Location</option>
                    <?php
                        foreach($location_select as $location_option => $key ) {
                            echo '<option value="'.$location_option.'"'.($_POST['location'] ?? null == $location_option ? ' selected' : '').'>'. $key .'</option>';
                            
                        }
                    ?>
                </select>
            </div>

        </div>

        <script type="text/javascript">
            document.getElementById('location').value = "<?php (!empty($_GET['location'])) ? print $_GET['location'] : print '0'; ?>";
        </script>

        <div class="col-12 col-md-2 d-flex px-0 d-flex justify-content-center justify-content-md-end pr-md-0 py-2 py-md-0">

            <button type="submit" class="btn my-3 my-md-auto"><i class="fa fa-search d-md-none d-lg-inline" aria-hidden="true"></i> To Buy</button>
        
        </div>
        
    </div>

</form>

Have searched online for something similar, maybe someone can tell me explain what I am looking for.

BOTÃO NOVA CONVERSA (APARECER USUÁRIOS AO CLICAR) [closed]

sou meio burrinho ainda, então estou programando aqui, porém estou com um problema que não consigo resolver que é o seguinte. Quando a pessoa faz o login no chat, ela deveria conseguir, caso não tenha histórico em nenhuma conversa, clicar no botão “Nova Conversa” e ver os usuários disponíveis, porém os usuários disponíveis não estão aparecendo assim que ela clica neste botão.

HTML:

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat em Grupo</title>
    <link rel="stylesheet" href="chat.css">
</head>
<body>
    <div id="chat-geral">
        <div id="aba-conversas">
            <h2>Conversas</h2>
            <button id="nova-conversa">Nova Conversa</button>
            <div id="lista-de-usuarios"></div>
        </div>
        <div id="chat">
            <div id="cabecalho">
                <span id="destinatario-atual"></span>
            </div>
            <div id="mensagens-chat"></div>
            <div id="input-mensagens">
                <input type="text" id="mensagem" placeholder="Digite sua mensagem">
                <button id="botao-enviar">Enviar</button>
            </div>
        </div>
    </div>
    <script src="chat.js"></script>
</body>
</html>

CSS:

body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    background-color: #f2f2f2;
    display: flex;
    flex-direction: column;
    height: 100vh;
}

#chat-geral {
    display: flex;
    flex: 1;
    justify-content: space-between;
    background-color: #fff;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    height: 100%;
}

#aba-conversas {
    flex: 1;
    padding: 20px;
    display: flex;
    flex-direction: column;
    background-color: #7f684b;
    color: #fff;
    border-top-left-radius: 8px;
    border-bottom-left-radius: 8px;
    position: relative;
}

#aba-conversas h2 {
    font-size: 20px;
    margin-bottom: 10px;
    display: center;
}

#lista-de-usuarios {
    display: none;
    flex-direction: column;
    position: absolute;
    top: 0;
    right: -220px;
    background-color: #fff;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    z-index: 1;
    color: white;
}

#nova-conversa {
    background-color: #916f47;
    color: #fff;
    border: none;
    padding: 10px 15px;
    font-size: 16px;
    border-radius: 4px;
    cursor: pointer;
    margin-top: auto;
    margin-bottom: 10px;
}

#nova-conversa:hover {
    background-color: #916f47;
}

#chat {
    flex: 2;
    display: flex;
    flex-direction: column;
    padding: 20px;
    border-top-right-radius: 8px;
    border-bottom-right-radius: 8px;
    background-color: #fff;
}

#cabecalho {
    font-size: 24px;
    margin-bottom: 10px;
}

#mensagens-chat {
    flex: 1;
    overflow-y: auto;
    border: 1px solid #ddd;
    padding: 10px;
    border-radius: 4px;
    background-color: #f9f9f9;
}

#mensagem {
    border: 1px solid #ddd;
    padding: 10px;
    border-radius: 4px;
    font-size: 16px;
    margin-top: 10px;
    width: 75%;
}

#botao-enviar {
    background-color: #7f684b;
    color: #fff;
    border: none;
    border-radius: 4px;
    padding: 10px 15px;
    font-size: 16px;
    cursor: pointer;
}

#input-mensagens {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

JS:

document.addEventListener('DOMContentLoaded', function () {
    var mensagemUsuario = {};

    document.getElementById('nova-conversa').addEventListener('click', function () {
        var usuariosDisponiveis = ['Usuário1', 'Usuário2', 'Usuário3'];

        var listaDeUsuarios = document.getElementById('lista-de-usuarios');
        listaDeUsuarios.innerHTML = '<h3>Usuários Disponíveis</h3>';

        usuariosDisponiveis.forEach(function (usuario) {
            var itemUsuario = document.createElement('div');
            itemUsuario.textContent = usuario;

            itemUsuario.addEventListener('click', function () {
                document.getElementById('destinatario-atual').textContent = 'Conversando com: ' + usuario;
                iniciarConversa(usuario);
            });

            listaDeUsuarios.appendChild(itemUsuario);
        });
    });

    document.getElementById('botao-enviar').addEventListener('click', function () {
        var destinatarioAtual = document.getElementById('destinatario-atual').textContent.replace('Conversando com: ', '');

        if (!destinatarioAtual) {
            alert('Escolha um destinatário primeiro!');
            return;
        }

        var inputMensagens = document.getElementById('mensagem');
        var mensagem = inputMensagens.value;

        if (mensagem.trim() !== '') {
            enviarMensagem(destinatarioAtual, mensagem);
            inputMensagens.value = '';
        }
    });

    function iniciarConversa(usuario) {
        if (!mensagemUsuario.hasOwnProperty(usuario)) {
            mensagemUsuario[usuario] = [];
        }

        mostrarMensagens(usuario);
    }

    function enviarMensagem(usuario, mensagem) {
        mensagemUsuario[usuario].push({
            envio: 'Você',
            mensagem: mensagem
        });

        mostrarMensagens(usuario);
    }

    function mostrarMensagens(usuario) {
        var mensagensChat = document.getElementById('mensagens-chat');
        mensagensChat.innerHTML = '';

        mensagemUsuario[usuario].forEach(function (msg) {
            var elementoMensagem = document.createElement('div');
            elementoMensagem.textContent = msg.envio + ': ' + msg.mensagem;
            mensagensChat.appendChild(elementoMensagem);
        });
    }
});

Intenção de que quando o usuário clicasse no botão nova conversa aparecesse a lista com os usuários disponíveis, porém não foi o que aconteceu.

Objects are not valid as a React child when setting state? [duplicate]

When setting state to an API response, I get the following error:

Objects are not valid as a React child (found: object with keys {id, name, repository_id, username, ip_addreess}). If you meant to render a collection of children, use an array instead.

Am I doing something wrong here? I’ve verified I’m setting the state to an array of objects, which should be fine as I set my state to an empty array initially.

Here is my component:

import React from "react";
import axios from "axios";
import withRouter from '../../helpers/withRouter';

class ListApplications extends React.Component<any, any> {
    constructor() {
        super({});

        this.state = {
            applications: []
        }

        this.getApplications = this.getApplications.bind(this);
    }

    async componentDidMount() {
        await this.getApplications();
    }

    async getApplications() {
        let component = this;

        await axios.get(process.env.REACT_APP_API_URL + '/applications')
            .then(async function (response : any) {
                component.setState({
                    applications: response.data,
                });
            })
            .catch(function (error : any) {
                console.log(error);
            });
    }

    render() {
        return (
            <>
                {this.state.applications.map(function(application: any, index: any) {
                    return (<>{application}</>)
                })}
            </>
        );
    }
}

export default withRouter(ListApplications);

Example of API response (/applications)

[
  {
    "id": 1,
    "name": "App1",
    "repository_id": 1,
    "username": "test",
    "ip_addreess": "127.0.01"
  },
  {
    "id": 2,
    "name": "App2",
    "repository_id": 2,
    "username": "root",
    "ip_addreess": "192.168.0.1"
  }
]

ember js – service usage to show data

I am new to ember js and trying to write my first app…

I have :

service app/service/event_handler.js

import Service from '@ember/service';

export default class EventHandlerService extends Service {

    eventList = [
        {
            EventName: 'test event 1',
            EventDesc: 'test event 1 desc',
            StartDate: '16.11.2023',
            EndDate: '05.02.2024',
            EventType_ID: 1,
        },
        {
            EventName: 'test event 2',
            EventDesc: 'test event 2 desc',
            StartDate: '17.11.2023',
            EndDate: '15.02.2024',
            EventType_ID: 2,
        },
        {
            EventName: 'test event 3',
            EventDesc: 'test event 3 desc',
            StartDate: '13.10.2023',
            EndDate: '01.01.2024',
            EventType_ID: 1,
        }
    ];
}

controller app/controllers/event-controller.js

import Controller from '@ember/controller';
import { getOwner } from '@ember/application';
import { service } from '@ember/service';
export default class EventControllerController extends Controller {
    // @service eventHandler;

    get events() {
        console.log("loading events");
        return getOwner(this).lookup('service:event-handler')
    }
}

and my hbs file that has a code block

<table>
                <thead>
                    <tr>
                        <th>Event name</th>
                        <th>Event Date Start</th>
                        <th>Event Date End</th>
                    </tr>
                </thead>
                <tbody>

                    {{#each this.eventHandler.eventList as |event|}}
                    <tr>
                        <td>{{event.EventName}}</td>
                        <td>{{event.StartDate}}</td>
                        <td>{{event.EndDate}}</td>
                    </tr>
                    {{/each}}
                </tbody>
            </table>

the table is empty and i dont know what am i doing wrong :c
I tried looking some tutorials and asking ai but I am still having issues…

Collision problems with octree in three.js

A three.js plane is only detecting collisions on one side of the geometry but not the other. The plane represents a wall where one side can be walked through but the opposite side is solid.

Both sides should should be solid. I have already attempted to modify the geometry to have normals on both sides but that did not work.

filter array by html select value react

I’m trying to filter my array by a select value but I’m not able to get the result I’m looking for. I want to be able to click a select option and the data re-renders with content relevant to that option but data is not displaying.

Here is an example of the array I’m trying to filter, I’m specifically targeting the contentType array.

[{ 
ageRange: [4, 7],
contentType: ['Animal Stories', 'Stories'],
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
flag: "New to Yoto",
handle: "5-minute-stories-in-the-wild",
id: 1,
imgSet: {sm: {…}, md: {…}, lg: {…}, alt: null},
price: "9.99",
productType: "single-card",
runtime: 1800,
title: "5-Minute Stories: In the Wild"
},
{
ageRange: [3, 10],
contentType: ['Action & Action', 'Stories'],
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
flag: "New to Yoto",
handle: "5-minute-stories-in-the-wild",
id: 2,
imgSet: {sm: {…}, md: {…}, lg: {…}, alt: null},
price: "3.99",
productType: "single-card",
runtime: 800,
title: "5-Minute Stories: In the Wild"
}]

Here is the code for my page:

import React, { useState, useEffect } from 'react';
import { sortBy } from '../utils/utils';
import { Products } from '../types/types';
import { fetchData } from '../endpoints/fetchData';
import '../index.css';

function App() {

     const sortBy: Record<string, any> = {
        duration: (prod: Products[]) => prod.sort((a, b) => a.runtime - b.runtime),
        price_ascending: (prod: Products[]) =>
          prod.sort((a, b) => parseInt(a.price) - parseInt(b.price)),
        price_descending: (prod: Products[]) =>
          prod.sort((a, b) => parseInt(b.price) - parseInt(a.price)),
        zero_to_five: (prod: Products[]) =>
          prod.filter((age) => age.ageRange[0] >= 0 && age.ageRange[1] <= 5),
        six_to_nine: (prod: Products[]) =>
          prod.filter((age) => age.ageRange[0] >= 6 && age.ageRange[1] >= 9),
      };

  const [products, setProducts] = useState<Products[]>([]);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [filterValue, setFilterValue] = useState<string>('');
  const [contentTypeValue, setContentTypeValue] = useState<string>('');

  const productsPerPage = 20;
  const lastIndex = currentPage * productsPerPage;
  const firstIndex = lastIndex - productsPerPage;
  const filteredProducts = sortBy?.[filterValue]?.(products) ?? products;
  const currentProducts = filteredProducts.slice(firstIndex, lastIndex);
  const pages = Math.ceil(filteredProducts.length / productsPerPage);
  const numbers = [...Array(pages + 1).keys()].slice(1);

  useEffect(() => {
    fetchData(setProducts);
  }, [contentTypeValue]);

  const nextPage = () => {
    if (currentPage !== lastIndex) {
      setCurrentPage(currentPage + 1);
    }
  };

  const prevPage = () => {
    if (currentPage !== firstIndex) {
      setCurrentPage(currentPage - 1);
    }
  };

  const movePages = (id: number) => {
    setCurrentPage(id);
  };

  const Pagination = () => {
    return (
      <nav>
        <ul>
          <li>
            <a
              href="#"
              className={`${currentPage === 1 ? 'none' : ''}`}
              onClick={prevPage}>
              Prev
            </a>
          </li>
          {numbers.map((number) => {
            return (
              <li key={number}>
                <a
                  href="#"
                  className={`${currentPage === number ? 'active' : ''}`}
                  onClick={() => movePages(number)}>
                  {number}
                </a>
              </li>
            );
          })}

          {filteredProducts.length <= 20 ? (
            <></>
          ) : (
            <li>
              <a
                href="#"
                className={`${currentPage === numbers.length ? 'none' : ''}`}
                onClick={nextPage}>
                Next
              </a>
            </li>
          )}
        </ul>
      </nav>
    );
  };

  const contentTypeList = [
    ...new Set(products.map((prod) => prod.contentType).flat()),
  ];

  const handleSort = (event: React.ChangeEvent<HTMLSelectElement>) => {
    setFilterValue(event?.target.value);
    //goto page 1 after sort
    setCurrentPage(1);
  };

  const handleContentTypeSort = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const value = e.target.value;
    setContentTypeValue(value);


    if (value) {
      return products.filter((content: Products) =>
        content.contentType.includes(contentTypeValue),
      );
    }
  };

  const mapContentTypes = () => {
    return (
      <>
        <select
          name="type"
          defaultValue=""
          data-testid="select"
          onChange={(e) => handleContentTypeSort(e)}>
          <option value="" selected defaultValue="Sort By:" disabled hidden>
            Content type
          </option>
          {contentTypeList.map((contentType) => (
            <option data-testid="type-option" value={contentType}>
              {contentType}
            </option>
          ))}
        </select>
      </>
    );
  };


  const mapProducts = () => {
    return (
      <React.Fragment>
        <div className="container">
          <div className="filterContainer">
            <div>
              <Pagination />
            </div>
            <div className="filter">
              <label htmlFor="type">Sort by: </label>
              <select
                name="type"
                defaultValue=""
                data-testid="select"
                onChange={handleSort}>
                <option
                  value=""
                  selected
                  defaultValue="Sort By:"
                  disabled
                  hidden>
                  Sort By
                </option>
                <option data-testid="type-option" value="price_ascending">
                  Price ascending
                </option>
                <option data-testid="type-option" value="price_descending">
                  Price descending
                </option>
                <option data-testid="type-option" value="duration">
                  Duration
                </option>
                <option data-testid="type-option" value="zero_to_five">
                  0-5
                </option>
                <option data-testid="type-option" value="six_to_nine">
                  6-9+
                </option>
              </select>
              <label htmlFor="type">Content Type: </label>
              {mapContentTypes()}

              <button>Reset filter</button>
            </div>
          </div>

          {currentProducts.map((product: Products) => {
            return (
              <div className="item" key={product.id}>
                <img className="image" src={product.imgSet.sm.src} />
                <div className="innerContainer">
                  <span>Name: {product.title}</span>
                  <span>Price: {product.price}</span>
                  <span>Stock level: {product.productType}</span>
                </div>
              </div>
            );
          })}
          <Pagination />
        </div>
      </React.Fragment>
    );
  };

  return (
    <header className="App-header">
      <div className="container">{mapProducts()}</div>
    </header>
  );
}

export default App;

Within this function here is where I’m trying to filter and trigger a re-render for my new data but the data is not displaying.

const handleContentTypeSort = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const value = e.target.value;
    setContentTypeValue(value);


    if (value) {
      return currentProducts.filter((content: Products) =>
        content.contentType.includes(contentTypeValue),
      );
    }
  };

I have pagination and other sorting functions working but this function doesn’t seem to working like I hope. I just need to able to click and it displays data to the relevant data per the contentType.

I have created a codeandsandbox to explain my code is doing and what is going wrong: https://codesandbox.io/s/runtime-night-w65s8z?file=/src/App.js

Kanban javascript html

I’m trying to learn javascript with an exercise where I try to create a kanban but I’m stuck. I can’t implement drag and drop. Anyone to help me? (ps I welcome any criticism regarding the code, I’m also here to learn)

I leave you the code below

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="boxDataEntry">
        <textarea id="containerDataEntry" cols="30" rows="10"></textarea>
        <button id="dataEntryButton">Enter</button>
    </div>

    <div id="boxDataContainer dropArea"></div>
    <div id="boxDataContainer1 dropArea"></div>

    <script src="./src/web/index.js"></script>
</body>
</html>

const button = document.getElementById("dataEntryButton");
const boxDataContainer = document.getElementById("boxDataContainer ");
const boxDataContainer1 = document.getElementById("boxDataContainer1");
const containerDataEntry = document.getElementById("containerDataEntry");

const createTable = (data) => {
    const div = document.createElement("div");
    const text = document.createElement("h1");
    const deleteTable = document.createElement("button");
    const makeDraggable = document.createAttribute("#")

    text.innerText = data;
    deleteTable.innerText = "Delete Table";

    deleteTable.addEventListener("click", () => {
        boxDataContainer .removeChild(div)
    });


    div.appendChild(text);
    div.appendChild(deleteTable)

    return (div);
}

dataEntryButton.addEventListener("click", () => {
    const data = containerDataEntry.value;

    const table = createTable(data);

    boxDataContainer.appendChild(table);
});


idk what to do, the point where I stopped is the one where I have to implement the drag and drop of the elements from one box to another and vice versa

How does one programatically map object values in Zod?

For the following schema:

const z_BaseCustomer = z.object({
  name: z.string(),
  age: z.number()
});

const pizzas = [
  {
    value: "pn_pizza",
    label: "Pineapple Pizza",
  },
  {
    value: "vgt_pizza",
    label: "Vegetarian Pizza",
  },
  {
    value: "sc_pizza",
    label: "Sicilian Pizza"
  },
  {
    value: "mg_pizza",
    label: "Pizza Margherita"
  },
  {
    value: "ny_pizza",
    label: "New York-Style Pizza"
  }
] as const;

type FavoritePizzaValue = typeof pizzas[number]['value'];
type FavoritePizzaLabel = typeof pizzas[number]['label'];
const z_FavoritePizzaValue = z.custom<FavoritePizzaValue>;
const z_FavoritePizzaLabel = z.custom<FavoritePizzaLabel>;

const drinks = [
  {
    value: "dr_cola",
    label: "Coca Cola"
  },
  {
    value: "dr_mtdew",
    label: "Mountain Dew"
  }
] as const;

type FavoriteDrinkValue = typeof drinks[number]['value'];
type FavoriteDrinkLabel = typeof drinks[number]['label'];
const z_FavoriteDrinkValue = z.custom<FavoriteDrinkValue>;
const z_FavoriteDrinkLabel = z.custom<FavoriteDrinkLabel>;


const z_ServerCustomer = z_BaseCustomer.extend({
  favorite_pizza: z_FavoritePizzaValue(),
  favorite_drink: z_FavoriteDrinkValue()
});

const z_ClientCustomer = z_BaseCustomer.extend({
  favorite_pizza: z_FavoritePizzaLabel(),
  favorite_drink: z_FavoriteDrinkLabel()
});

type ServerCustomer = z.infer<typeof z_ServerCustomer>;
type ClientCustomer = z.infer<typeof z_ClientCustomer>;

My goal is to map objects of these two types to each other, such that the data in ServerCustomer is stored in my database and ClientCustomer is rendered in the browser.

Is there a better way than just..?:

const CustomerUnionSchema = z.discriminatedUnion("favorite_pizza", [
  z_ServerCustomer, z_ClientCustomer
]).transform(customer => {
  if(customer.favorite_drink === 'dr_cola' && customer.favorite_pizza === 'mg_pizza'){
    return {...customer, favorite_drink: "Coca Cola", favorite_pizza: "Pizza Margherita"}
  } else if (customer.favorite_drink === 'dr_cola' && customer.favorite_pizza === 'ny_pizza'){
    return {...customer, favorite_drink: "Coca Cola", favorite_pizza: "New York-Style Pizza"}
  } else if ( 
    ...//
});

Searching through the Zod documentation returned nothing, same on here. Is there a way Zod can infer the mapping of these types? Moreover, should I rather change my approach to typing my data? What would be considered best?

Issue with Retrieving Filter Values in DataTables fnServerParams Callback

I am facing an unusual issue with DataTables in my web application. I’m trying to retrieve the values of filters (specifically a date filter) in the fnServerParams callback of DataTables, but I’m not getting the expected results.

Here’s a snippet of the code I’m using:

var localCurrentFilters = {};

console.log(aoData);
aoData.forEach(function(item) {
    console.log("Key:", item.name, "Value:", item.value); // Debug log
    localCurrentFilters[item.name] = item.value;
});
// Call highlightActiveFilters with the current filters
highlightActiveFilters(localCurrentFilters);

In this code, I’m iterating through aoData to construct a localCurrentFilters object that is supposed to contain the values of the active filters.

However, while I can see the correct values (e.g.,”sSearch_1″ = “01-11-2023~30-11-2023”) when I log aoData directly,
enter image description here

the values associated with keys in localCurrentFilters often turn out to be empty.

enter image description here

This issue is particularly happening with date filters, where I expect to see a string formatted as “01-11-2023~30-11-2023”, but end up with an empty or incomplete string.

I am looking for suggestions on what might be causing this issue or how I can effectively capture these filter values. Any insights or advice would be greatly appreciated.

Thank you!

str.replace is not a function in react-select

I am returning objects from the backend to fill them in the select component but for some reason when I receive the data I get the error str.replace is not a function and when I do not receive data (that is, there are no matches) the select field shows the [Object Promise] text and I can’t change or delete it.

const [selectedMedico, setSelectedMedico] = useState(null);
const [medicoOptions, setMedicoOptions] = useState([]);

const handleSearch = async (inputValue) => {
    try {
      const response = await axios.get(`http://localhost:3000/api/users/buscar-usuarios?search=${inputValue}`);
      const medicoData = response.data; // Array de objetos con la información del médico
      const options = medicoData ? medicoData.map((medico) => ({ value: medico._id, label: `${medico.nombre} ${medico.apellido}` })) : [];
      setMedicoOptions(options);
    } catch (error) {
      console.error('Error al realizar la búsqueda:', error);
      // Puedes imprimir más información sobre el error, por ejemplo:
      console.error('Error response:', error.response);
      console.error('Error message:', error.message);
      // ...
    }
  };



<div className="row mb-3">
                    <label htmlFor="inputMedico" className="col-sm-2 col-form-label">Médico</label>
                    <div className="col-sm-10">
                      <Controller
                        name="medico"
                        control={control}
                        rules={{ required: "El nombre del médico es obligatorio" }}
                        render={({ field, fieldState }) => (
                          <Select
                            {...field}
                            id="inputMedico"
                            name="medico"
                            placeholder="Seleccione un médico"
                            value={selectedMedico}
                            options={medicoOptions}
                            onChange={(value) => {
                              field.onChange(value);
                              setSelectedMedico(value instanceof Promise ? null : value);
                            }}
                            onInputChange={(inputValue) => handleSearch(inputValue)}
                          />
                        )}
                      />
                    </div>
                  </div>

Issue with Office.context.mailbox.getCallbackTokenAsync for shared mailbox

`I’m encountering an issue with the Office.context.mailbox.getCallbackTokenAsync function in my Office Add-in from office 365. The function works fine for a non-shared inbox but returns an error for a shared inbox.

Below is the code I am using

`Office.context.mailbox.getCallbackTokenAsync(
{ isRest: true },
(result: any) => {

                if (result.status === "succeeded") {
                    var accessToken = result.value;
                    console.log(accessToken);
                    this.getWebUrl()
                        .then((itemId) => {

                            
                } else {
                    
                    reject(result);
                    
                }
            }
        );
    });
    
}`

Issue Details:

  • Error Message: OSF.DDA.Error {name: 'GenericTokenError', message: 'An internal error has occurred.', code: 9018}
  • Scenario: Works for non-shared inbox, but fails for Shared inbox.
  • Expected Outcome: Successful retrieval of access token for shared inbox.`

Questions:

  • Has anything changed with "getCallbackTokenAsync" recently that might affect its behavior with shared inboxes?
  • Are there specific permissions or configurations required for accessing shared mailboxes using “getCallbackTokenAsync”?
  • Can anyone please suggest any solution to this or anything that would help me resolve this?`

When nesting in JS-“while loop” variable is not defined anymore

My JS-script checks, if the database has values. if it does not it fills the database. When triggered again the values from the database are displayed on the page. This works when I run te script twice by reloading the page. When I but the whole thing in a while loop it does not work at all. The loop runs forever because I guess it cannot enter the marmaInfo.onsuccess = function(evt) {
I’m not sure if it is a scope problem, i just cant figure it out, why it behaves differently when the while loop is active.

let i = 0;
//while (i < 1) {
    var marmaInfo = store.get(key);
    marmaInfo.onsuccess = function(evt) {
        var req = store.openCursor(key);
        var record = evt.target.result;
        console.log("record:", record);
        req.onsuccess = function(e) {
          var cursor = e.target.result; 
          if (cursor !== null) { // key already exist
            console.log(key + " FOUND");
            console.log("load and display values of " + key);
            data = marmaInfo.result
            //build page
            // Marma information
            document.getElementById("headline").innerHTML = data.sanskrit;
            console.log("display values of " + key + " DONE");
            i++;
          } else { // key not exist
            console.log(key + " NOT FOUND");
            console.log("initial filling DB ...");
            initialMarmaData.forEach((marma) => {
                var request = store.put(marma);
                request.onsuccess = (event) => {
                    console.log(event.target.result + " initial filling DB DONE");
                };
            //return;
            });
            //store.add(obj)
          }
        };
    };
    marmaInfo.onerror = function(evt) {
        console.log("error");
        i++;    
    }
//}

How to get tsParticles behind the rest of the elements in my NextJS project?

I’ll preface by highlighting that I am not a webdev, so I could have my entire setup wrong.

With this current code, the particles cover all the other elements, and I’d like to get it behind the rest of the elements and only show as a background.

import Image from 'next/image'
import{AiFillLinkedin, AiFillGithub} from 'react-icons/ai'
import deved from "../public/dev-ed-wave.png";
import code from "../public/code.png";
import design from "../public/design.png";
import ParticleBackground from './components/particle';

export default function Page() {
  return (  
    <div>
      <div>

      <>
      
      <ParticleBackground/>
      
      </>

      </div>
        <head>
          <title>Portfolio</title>
            <meta name="description" content='Blank'></meta>
            <link rel='icon' href='/icon.ico' type='image/x-icon'/>
        </head>
        <main className='bg-white px-10 dark:bg-black md:px-20 lg:px-40, z-2'>
          <section className='min-h-screen'> 
            <nav className='py-10 mb-12 flex justify-between'>
              <h1 className='text-xl'>madebye :)</h1>
              <ul className='flex items-center'>
              <li><a className='text-white px-4 py-2 rounded-md ml-8 border-solid border-2 border-purple-400' href=''>Resume</a></li>
            </ul>
          </nav>
          <div className='text-center p-10'>
            <h2 className='text-5xl py-2 text-purple-400 font-medium'>Evan Quah</h2>
            <h3 className='text-2xl py-2'>
              
              System Administrator and Security Student
              
            </h3>
            <p className='text-medium py-5 leading-8 md:text-xl max-w-xl mx-auto'>
              blah blah blah fix later
            </p>
          </div>
          <div className='text-5xl flex justify-center gap-16 py-3'>
            <a href=''>
            <AiFillGithub />
            </a>
            <a href=''>
            <AiFillLinkedin />
            </a>
          </div>
          <div className='derrelative mx-auto bg-gradient-to-b from text-teal-500 rounded-full w-80 h-80 mt-20 overflow-hidden md:h-96 md:w-96'>
            <Image src={deved} />
          </div>
        </section>
        
        <section>
          <div>
            <h3 className='text-3xl py-1'>Who I am</h3>
            <p className='text-medium py-5 leading-8'>
            
            Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

            </p>
          </div>
            <div className='lg: gap-10'>
              <div className='text-center shadow-lg p-10 rounded-xl my-10 border-solid border-2 border-purple-400'>
                <div className='flex justify-center items-center'>
                  <Image src={design} width={100} height={100} />
                </div>
                <h3 className='text-lg font-medium pt-8 pb-2'>
                  
                  Home Lab
                  
                  </h3>
                <p>
                
                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

                </p>
                <h4 className='py-4 text-purple-400'> Tools I use</h4>
                <p className='text-gray-200 py-1'>Linux</p>
                <p className='text-gray-200 py-1'>Docker</p>
                <p className='text-gray-200 py-1'>Azure</p>
            </div>
            <div className='lg: gap-10'>
              <div className='text-center shadow-lg p-10 rounded-xl my-10 border-solid border-2 border-purple-400'>
                <div className='flex justify-center items-center'>
                  <Image src={design} width={100} height={100} />
                </div>
                <h3 className='text-lg font-medium pt-8 pb-2'>
                  
                  Things I make
                  
                  </h3>
                <p>
                
                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
                
                </p>
                <h4 className='py-4 text-purple-400'> Tools I use</h4>
                <p className='text-gray-200 py-1'>Nmap</p>
                <p className='text-gray-200 py-1'>Wireshark</p>
                <p className='text-gray-200 py-1'>Azure</p>
            </div>
          </div>
          <div className='lg: gap-10'>
              <div className='text-center shadow-lg p-10 rounded-xl my-10 border-solid border-2 border-purple-400'>
                <div className='flex justify-center items-center'>
                  <Image src={design} width={100} height={100} />
                </div>
                <h3 className='text-lg font-medium pt-8 pb-2'>
                  
                  Things I make
                  
                  </h3>
                <p>
                
                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
                
                </p>
                <h4 className='py-4 text-purple-400'> Tools I use</h4>
                <p className='text-gray-200 py-1'>Nmap</p>
                <p className='text-gray-200 py-1'>Wireshark</p>
                <p className='text-gray-200 py-1'>Azure</p>
            </div>
          </div>
          </div>
        </section>
        <section>
          <div>
            <h3 className='text 3xl py-1'>Portfolio</h3>
            <p className='text-medium py-5 leading-8'>
            
            Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
            Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
            <span className="text-purple-400"> agencies </span>
            consulted for <span className="text-purple-400">startups </span>
            and collaborated with talanted people to create digital products
            for both business and consumer use.
            
            </p>
          </div>
        </section>
        </main>
    </div>
    )
}

Here is my particle.jsx file as well:

'use client'

import React from 'react';
import { useCallback } from 'react';
import { loadFull } from 'tsparticles';
import Particles from 'react-tsparticles';

const ParticleBackground = () => {
  const particlesInit = useCallback(async (engine) => {
    console.log(engine);
    // you can initiate the tsParticles instance (engine) here, adding custom shapes or presets
    // this loads the tsparticles package bundle, it's the easiest method for getting everything ready
    // starting from v2 you can add only the features you need reducing the bundle size
    await loadFull(engine);
  }, []);

  const particlesLoaded = useCallback(async (container) => {
    await console.log(container);
  }, []);
  return (
    <div id='particle-background'>
      <Particles
        id='tsparticles'
        particlesLoaded='particlesLoaded'
        init={particlesInit}
        loaded={particlesLoaded}
        options={
            
            {background: {
                color: {
                    value: "#0d47a1",
                },
            },
            fpsLimit: 120,
            interactivity: {
                events: {
                    onClick: {
                        enable: true,
                        mode: "push",
                    },
                    onHover: {
                        enable: true,
                        mode: "repulse",
                    },
                    resize: true,
                },
                modes: {
                    push: {
                        quantity: 4,
                    },
                    repulse: {
                        distance: 200,
                        duration: 0.4,
                    },
                },
            },
            particles: {
                color: {
                    value: "#ffffff",
                },
                links: {
                    color: "#ffffff",
                    distance: 150,
                    enable: true,
                    opacity: 0.5,
                    width: 1,
                },
                move: {
                    direction: "none",
                    enable: true,
                    outModes: {
                        default: "bounce",
                    },
                    random: false,
                    speed: 6,
                    straight: false,
                },
                number: {
                    density: {
                        enable: true,
                        area: 800,
                    },
                    value: 80,
                },
                opacity: {
                    value: 0.5,
                },
                shape: {
                    type: "circle",
                },
                size: {
                    value: { min: 1, max: 5 },
                },
            },
            detectRetina: true,
        }}

        height='100vh'
        width='100vw'
        z-index='1'
      ></Particles>
    </div>
  );
};

export default ParticleBackground;

I am trying to get a website with tsParticles in the background, and the rest of the site elements in the front. Right now I am only able to get one or the other. If I remove the “ParticlesBackground” tag then the rest of the site will show, but if I leave it in it covers the rest of the page. Anyone know how I might fix this? I’m using NextJs and TailwindCSS.