Full calendar react add our own div in headertoolbar

I want to add my own div which has a react select in full calendar headertoolbar left.

   <FullCalendar
      plugins={[ dayGridPlugin ]}
      initialView="dayGridMonth"
      weekends={false}
      events={[
        { title: 'event 1', date: '2019-04-01' },
      ]}
      headerToolbar={{
        left: '',
        center: 'prev,title,next',
        right: ''
      }}
    />

This is the sample Full calendar, In headertool left I need to add my own div for example

    <div className='option-select'>
    <label >
        Pick a fruit:
        <select name="selectedFruit">
          <option value="apple">Apple</option>
          <option value="banana">Banana</option>
          <option value="orange">Orange</option>
        </select>
    </label>
    </div>

Here in headertool left I need to add this div in it.
Is it possible to do it?

React Testing Library + React Query – promise isn’t resolved while testing

I’m using React 18, React Testing Library 14.0.0, and React Query 3.3. Everything is working like a charm in the browser (real user) context. But while testing I am experiencing some problems.

My component (simplified):

import { useQuery } from "react-query"

export const Dashboard = () => {
    const { data } = useQuery(...)
    const { data: project } = useQuery(...)

return <div data-testid="project-name">{project.name}</div>

The test:

import { ReactElement, Suspense } from "react"
import { render } from "@testing-library/react"
import { QueryClient } from "react-query"

export const testRenderer = (test: ReactElement) => 
render(<Suspense fallback={<div>loading...</div>}>
  <QueryClientProvider
    client={
      new QueryClient({
        defaultOptions: {
          queries: {
            suspense: true,
          },
        },
      })
    }
  >{test}</QueryClientProvider>
</Suspense>);

The test:

import { waitFor } from "@testing-library/react";

test("render it", async () => {
  const { getByTestId } = testRenderer(<Dashboard />);

  await waitFor(async () => await findByTestId("project-name"));
  await waitFor(() => findByTestId("project-name"));
});

As a result, I see the FAIL Timed out in waitFor.:

<body>
  <div>
    <div>loading...</div>
  </div>
</body>

So it’s pretty apparent <Suspense /> is waiting for the react-queries to be finished before rendering the real component body.

When I wrap react queries into a try/catch I see as a result of console.log(error): Promise { <pending> } so the promises are pending for some reason while I reach waitFor.

How can I fix it or even debug deeply what’s wrong with react-query?

Webpack (mini-css-extract-plugin) Error: Multiple chunks emit assets to the same filename app.js (chunks src and css)

I’ve been toiling with this for a while, and even with the broadly unintelligible structure of webpack, I can’t find any guidance on how this is supposed to work.

Context:

I have multiple JS files and multiple CSS files. I want to combine them for production deployment. I’ve been using webpack for a while successfully with just JS, but trying to add CSS yields an error:

Error: Conflict: Multiple chunks emit assets to the same filename app.js (chunks src and css)
    at /<redacted>/node_modules/webpack/lib/Compilation.js:4617:12
    at /<redacted>/node_modules/webpack/lib/Cache.js:91:34
    at Array.<anonymous> (/<redacted>/node_modules/webpack/lib/cache/MemoryCachePlugin.js:45:13)
    at /<redacted>/node_modules/webpack/lib/Cache.js:91:19
    at Hook.eval [as callAsync] (eval at create (/<redacted>/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:19:1)
    at Cache.get (/<redacted>/node_modules/webpack/lib/Cache.js:75:18)
    at ItemCacheFacade.get (/<redacted>/node_modules/webpack/lib/CacheFacade.js:111:15)
    at /<redacted>/node_modules/webpack/lib/Compilation.js:4563:22
    at arrayEach (/<redacted>/node_modules/neo-async/async.js:2405:9)
    at Object.each (/<redacted>/node_modules/neo-async/async.js:2846:9)

My webpack.config.js file looks like this:

import path from 'path';
import {fileURLToPath} from 'url';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';

// __dirname doesn't work with ES6 modules :/
// https://bobbyhadz.com/blog/javascript-dirname-is-not-defined-in-es-module-scope
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export default {
  entry: {
    src: './src/index.js',
    css: [
      path.resolve(__dirname, './css/styles.css'),
      path.resolve(__dirname, './css/properties.css'),
    ]
  },

  devtool: "source-map",
  output: {
    path: path.resolve(__dirname, 'dev'),
    filename: 'app.js',
    library: "app"
  },
  module: {
    rules: [
      {
        test: /.css$/,
        use: [
          MiniCssExtractPlugin.loader, 
          "css-loader"
        ],
      },
    ],
  },
  plugins: [new MiniCssExtractPlugin({
    filename: 'app.css',
  })]
};

My goal is to have multiple css files and multiple js files merged (and minified) into a single JS (app.js) and a single CSS file (app.css).

Has anyone been able to get this working?

Environment

From package.json

"css-loader": "^6.7.1",
"mini-css-extract-plugin": "^2.7.3",
"source-map-loader": "^4.0.0",
"webpack": "^5.74.0",
"webpack-cli": "^5.0.1"

Node version:

node --version
v14.17.1

Array gets the same value as an element from input

I would like to make an input (later function that adds more)

Then while user write some kind of number, the array gets it as an element instantly.

When I have 5 inputs with numbers, the array also has that 5 values in order ofc and that all like automatically added.

How can I do it?

I found really good video on YouTube but its’s React and I am only interested in JavaScript.

How do I fetch Multiple Specific Rows in Supabase JS?

I have 2 tables Clients and Contacts

I have a table with a cell with specific user IDs in the client table called “contacts”
image

How do I fetch the specific rows from the contacts table from the contacts array found in the client table?

Getting the array is easy enough

let associatedContactsArray = [];

async function getAssociatedContactsID() {
        const { data: contacts, error } = await supabaseClient
            .from('clients')
            .select('contacts')
            .eq('id', $clientID);
        if (contacts) {
            const [fetchedContacts] = contacts;
            if (fetchedContacts.contacts != null) {
                associatedContactsArray = fetchedContacts.contacts;
                hasAssociatedContacts = true;
                console.log('ASSOCIATED CONTACTS', associatedContactsArray);

                getAssociatedContacts();
            } else {
                console.log('THERE ARE NO CONTACTS');
                hasAssociatedContacts = false;
            }
        }

        if (error) {
            console.log('ERROR GETTING ASSOCIATED CONTACTS', error);
        }
    }

The following does not work.

    async function getAssociatedContacts() {
        const { data: contacts, error } = await supabaseClient
            .from('contacts')
            .select('*')
            .filter('id', 'in', { associatedContactsArray });
        if (contacts) {
            const [fetchedContacts] = contacts;
            if (fetchedContacts.contacts != null) {
                console.log('GOT CONTACT DETAILS');
                console.log('CONTACTS', contacts);
            } else {
                console.log('NO CONTACT DETAILS');
                hasAssociatedContacts = false;
            }
        }

        if (error) {
            console.log('ERROR GETTING ASSOCIATED CONTACTS', error);
        }
    }

I get the error:
{ "code": "PGRST100", "details": "unexpected "[" expecting "("", "hint": null, "message": ""failed to parse filter (in.[object Object])" (line 1, column 4)" }

Referencing Match the Filter: https://supabase.com/docs/reference/javascript/filter

Display array on react-pdf

I’m creating a pdf using react-pdf library. When I pass direct data, like strings or numbers, everything is right. The issue is when I pass an array in props. This is the array called ‘books’:

[
    {
        "id": "63e6c5939c4408def54db54a",
        "copies": 100,
        "_id": "63f6386a35f07f585176e778"
    },
    {
        "id": "63e6c5f59c4408def54db54e",
        "copies": 100,
        "_id": "63f6386a35f07f585176e779"
    },
    {
        "id": "63e6c64f9c4408def54db552",
        "copies": 150,
        "_id": "63f6386a35f07f585176e77a"
    },
    {
        "id": "63ecdc95105db694012e914d",
        "copies": 100,
        "_id": "63f6386a35f07f585176e77b"
    }
]

So, here is the React component for rendering the pdf:

/* eslint-disable arrow-body-style */
/* eslint-disable react/prop-types */
/* eslint-disable no-unused-vars */
import {
  Page,
  Text,
  View,
  Document,
  StyleSheet,
  Image,
  // Font,
} from '@react-pdf/renderer';

// Create styles
const styles = StyleSheet.create({
  page: {
    flexDirection: 'column',
    backgroundColor: '#FFF',
    margin: 25,
    fontSize: 10,
    // fontFamily: 'Roboto',
  },
  date: {
    marginBottom: 20,
  },
  publisherData: {
    flexDirection: 'row',
    gap: 20,
  },
  publisherLogo: {
    width: '100%',
  },
  header: {
    fontSize: 14,
    fontWeight: 'bold',
    alignSelf: 'center',
    marginTop: 20,
  },
});

// Create Document Component
const EntryPdf = ({
  publisher, logo, pubId, internalId, date, books,
}) => (
  <Document>
    <Page size="LETTER" style={styles.page}>
      <Text style={styles.date}>{date}</Text>
      <View style={styles.publisherData}>
        <View style={{ width: '10%' }}>
          <Image src={logo} style={styles.publisherLogo} />
        </View>
        <View>
          <Text>{publisher.name}</Text>
          <Text>{pubId.type}: {pubId.number}</Text>
          <Text>Dirección: {publisher.address}</Text>
          <Text>Teléfono: {publisher.phone}</Text>
          <Text>Correo electrónico: {publisher.email}</Text>
        </View>
      </View>
      <Text style={styles.header}>Ingreso de ejemplares</Text>
      <Text>Ingreso No. {internalId}</Text>
      {books && Array.isArray(books)
        ? books.map((book) => (
          <View key={book.id}>
            <Text>Id: {book.id}</Text>
            <Text>Copies: {book.copies}</Text>
          </View>
        ))
        : null}
    </Page>
  </Document>
);

export default EntryPdf;

The problem is that on the pdf, only data from position 0 of the books array is being displayed.
enter image description here

What should I use for pdf render all elements in the array?

Thank you!

what happens if i add the array as a member of the same array? [duplicate]

so i am learning javascript and i got curious what would happen if i
add an array as a member to the same array like this:

const arrayInSameArray = ["just a", 1986, "random string"];

arrayInSameArray[arrayInSameArray.length - 1] = arrayInSameArray;

console.log(arrayInSameArray);

i am just curious if it will go infinitely or will stop at some point, because in a browser console i just keeps opening

i opened it a couple times in browser console and it just kept going deeper and deeper.
i tried to find an answer in internet but all i found was combining two arrays together, which is not the case.

i would be glad if you could give me an answer!

React useState and useEffect issue

import axios from 'axios';
import React, { useEffect, useState} from 'react';
import pkceChallenge from 'pkce-challenge';
import { useCookies } from 'react-cookie';


function Login({ onLogin }) {

  const [cookies, setCookie] = useCookies('accessToken');
  const [codeVerifier, setCodeVerifier] = useState({});

  useEffect(() => {
    const urlParams = new URLSearchParams(window.location.search);
    const code = urlParams.get('code');
    if (code) {
      retrieveToken(code);
      window.history.replaceState({}, document.title, window.location.pathname);
    }
  }, [codeVerifier]);

  const handleLogin = () => {

    const challenge = pkceChallenge();
    setCodeVerifier(challenge.code_verifier);
  
    window.location.href = 'http://localhost:8080/oauth2/authorize?' +
      'response_type=code&' +
      'client_id=client&' +
      'scope=openid&' +
      'redirect_uri=http://127.0.0.1:3000/login&' +
      'code_challenge=' +
      challenge.code_challenge +
      '&' +
      'code_challenge_method=S256';
  };

  const retrieveToken = (code) => {
    
    try {
      const response = axios.post(
        'http://localhost:8080/oauth2/token?' +
        'client_id=client&' +
        'redirect_uri=http://127.0.0.1:3000/login&' +
        'grant_type=authorization_code&' +
        'code=' + code + '&' +
        'code_verifier=' + codeVerifier
      );
      setCodeVerifier('');
      const accessToken = response.data.access_token;
      const options = {
        path: '/',
        expires: new Date(new Date().getTime() + response.data.expires_in * 1000), 
      };
      setCookie('accessToken', accessToken, options);
      onLogin()
    } catch (err) {
      alert('Invalid Credentials');
    }
  };


  return (
    <div>
      <h2>Login</h2>
      <button onClick={handleLogin}>Login</button>
    </div>
  );
}


export default Login;

Current workflow: When user press login, authorization code will be delivered and right after i want to send a request to the /login with this authorize code and the code verifier that i have just set when the user pressed login, but the codeVerifier is always null. What is the problem?

Lit element innerHTML showing incorrect value

When using an on click event to get the value of clicked element, using .innerHTML it returns the lit element ID too:

<input
  type="radio"
  value=${item.value}
  .checked=${item.checked}
  @click=${this.toggleRadioCheck}
>

toggleRadioCheck(e) {
  console.log(e.target.innerHTML); // Result: <!--?lit$5487646469$-->Input One
  console.log(e.target.value); // Result: Input One
}

As you can see using e.target.value is returning the correct value but using e.target.innerHTML picks up the LIT ID too. When lit components are rendered in shadow DOM LIT attaches a commented ID associated to the component, but hoping there was a way to use innerHTML to get the value.

How can avoid returning the ID generated by LIT. This:

What is the best way to automate background database updates of a front-end app?

I have a JS app (deployed on Vercel) where users can leave reviews of places. What I’d like is, when you open a place’s page, to see the number of reviews and the average value of those reviews. But I don’t want to do this query on that page (to gain load speed). And I also don’t want to do it when submiting a review (also so the user doesn’t have a big load).

I first tought about a serverless function which would be trigerred upon submiting a review. But how could I trigger that function without the app having to wait for it to be done? It would run in the background not blocking the app

Update useMemo data in react-table

I’ve just started working with react-table and I can’t figure out how to use use Memo when loading a page yet. How do I push data(from api) into const data when loading a page.

import React, { useEffect, useState, useMemo } from "react";
import "../../custom.css";
import {COLUMNS} from './columns';
import { useTable } from "react-table";
import { ButtonGroup } from "../ButtonMenu";
import ChildInput from "../ChildInput/ChildInput";
import ChildModal from "../ChildModal/ChildModal";

export default function ChildTableNew() {
  const [childrens, setChildrens] = useState([]);
  const [selectedRow, setSelectedRow] = useState(-1);
  const [loading, setLoading] = useState(true);
  const [createModal, setCreateModal] = useState(false);
  const columns = useMemo(() => COLUMNS, [])
  const data = useMemo(() => childrens, [childrens])

  const [name, setName] = useState("");

  useEffect(() => {
    Get();
    console.log(data);
  }, []);

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    footerGroups,
    rows,
    prepareRow
  } = useTable({
    columns,
    data
  })
  

  return (
    loading? 
    <p>
      <em>Loading...</em>
    </p> : 
    <div>

      <ChildModal visible={createModal} setVisible={setCreateModal}>
      <form>
        <ChildInput 
        value={name} 
        onChange={e => setName(e.target.value)} 
        type="text" 
        placeholder="Имя"/>

        <ChildInput type="text" placeholder="Фамилия" />
        <ChildInput type="text" placeholder="Отчество" />
        <ChildInput type="date" placeholder="Дата рождения" />
        <select className=".sex" >
        <option disabled> Пол </option>
        <option value="мальчик"> мальчик </option>
        <option value="девочка"> девочка </option>
        </select>
        <ChildInput type="text" placeholder="Полис" />
        <ChildInput type="text" placeholder="Адрес" />
        <div class="btn-group" role="group" aria-label="Basic example">
        <button type="button" class="btn btn-add" onClick={Add}>
          Создать
        </button>
        <button type="button" class="btn btn-delete" onClick={() => setCreateModal(false)}>
          Закрыть
        </button>
        </div>
      </form>
      </ChildModal>

      <div class="btn-group" role="group" aria-label="Basic example">
        <button type="button" class="btn btn-add" onClick={() => setCreateModal(true)}>
          Add
        </button>
        <button type="button" class="btn btn-update">
          Update
        </button>
        <button type="button" class="btn btn-delete" onClick={Delete}>
          Delete
        </button>
      </div>
      
      <table {...getTableProps()}>
        <thead>
          {headerGroups.map(headerGroup => (
            <tr {...headerGroup.getHeaderGroupProps()}>
              {headerGroup.headers.map(column => (
                <th {...column.getHeaderProps()}>{column.render('Header')}</th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody {...getTableBodyProps()}>
          {rows.map(row => {
            prepareRow(row)
            return (
              <tr {...row.getRowProps()}>
                {row.cells.map(cell => {
                  return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
                })}
              </tr>
            )
          })}
        </tbody>
        <tfoot>
          {footerGroups.map(footerGroup => (
            <tr {...footerGroup.getFooterGroupProps()}>
              {footerGroup.headers.map(column => (
                <td {...column.getFooterProps()}>{column.render('Footer')}</td>
              ))}
            </tr>
          ))}
        </tfoot>
      </table>
      </div>
  );

  async function Add(e){
    e.preventDefault()
    console.log(name)
    setCreateModal(false)
  }
  async function Delete(){

  }
  
  async function Get() {
    const response = await fetch("api/Children");
    const data = await response.json();
    setChildrens(data);
    setLoading(false);
  }
}

Now I’m using useEffect to get data for a table from the api (I have a working regular table, but I want to move it to react-table).

Why do I have to rerun the server on every change of my react app?

I’m making my first project using react, until now I never used any other framework, only pure html+js+php+nodejs.
So, I was building a portfolio spa, but I’ve got this issue. When I make any change in the project, I have to restart the entire server to make it actualize. I’m pretty sure it’s not supposed to happen.

to be more precise, I’ve created a react app using cra (npx create-react-app if I remember) and I’m running the server with “npm start”.

This aside, I’m using VSC as my IDE on Win 11 and my terminal is on wsl: kali linux

Here is my App.js

import React from 'react';
import './App.css';
import './layer1.svg';
import Menu from './components/menu';
import Portfolio from './components/portfolio'
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'





function App() {
  return (
  <div>
    <Menu/>
    <Router>
        <Routes>
        <Route path="/portfolio" element={<Portfolio />}/>
        <Route exact path="/" element={<Portfolio />}/>
        </Routes>
    </Router>
    </div>
  );
}

export default App;

here is my index.js:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
if (module.hot) {
  module.hot.accept();
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);



I’ve made a lot of research to try to solve my issue, here’s what I tried:

  1. increasing my max user watches to 524288
  2. adding a “.env” file with FAST_REFRESH=false in it
  3. adding:
if (module.hot) {
  module.hot.accept();
}

into my index.js

  1. modifying my package.json .scripts:
  "scripts": {
    "start": "CHOKIDAR_USEPOLLING=true react-scripts start", //here
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

but nothing works.

I am expecting the changes to appear in my browser, either auto, or even by reloading the page.

Huge thanks to anyone that can help me 🙂

Bind parameters must be array if namedPlaceHolder parameter is not enabled error

I’m reworking my question as I completely redesigned my API because of a key issue. The fact I have a “file” and it’s a multipart/form-data, I needed a form handler since NextJS doesn’t have one. So I worked it around “multiparty”, where I can actually parse the multipart/form-data coming in from the form. This is the API I use now:

import mysql from "mysql2/promise";
import multiparty from "multiparty";

export default async function handler(req, res) {
  const dbconnection = await mysql.createConnection({
      host: "localhost",
      database: "onlinestore",
      port: 3306,
      user: "root",
      password: "Jennister123!",
  });
  try {
    const form = new multiparty.Form()

    const data = await new Promise((resolve, reject) => {
      form.parse(req, function (err, fields, files) {
        if (err) reject({ err })
        resolve({ fields, files })
      })
    })
const query = `INSERT INTO games (ProductID, ProductName, ProductDescription, ProductImage, ProductPrice, DateWhenAdded) VALUES ("${data.fields.ProductID}", "${data.fields.ProductName}","${data.fields.ProductDescription}","${data.fields.ProductImage}","${data.fields.ProductPrice}","${data.fields.DateWhenAdded}")`
    await dbconnection.execute(query, data);
   
    dbconnection.end();
    
    
    data.forEach((games) => {
        games.ProductImage = "data:image/webp;base64," + games.ProductImage.toString('base64');
    }
    );
    data.forEach((games) => {
        var d = new Date(games.DateWhenAdded);
        var now = moment(d).format('l');
        console.log(now);
    }
    );
    res.status(200).json({ games: data });
    

} catch (error) {
    res.status(500).json({ error: error.message });
}
}
export const config = {
  api: {
    bodyParser: false,
  }
}

And obviously from another question, this is the form I’m using:

<!DOCTYPE html>
<html lang = "en">
<head>
<title>
New Game Addition
</title>
</head>
<body>
<form method="post" action="/api/newgame" enctype="multipart/form-data">
    <input type="number" id = "ProductID" name="ProductID" placeholder="Product ID"> <br />
    <input type="text" id = "ProductName" name="ProductName" placeholder="Name of Product."> <br />
    <input type="text" id = "ProductDescription" name="ProductDescription" placeholder="Describe the Product."> <br />
    <input type="file" id = "ProductImage" name="ProductImage" placeholder="Put in Image"> <br />
    <input type="number" step="0.01" id = "ProductPrice" name="ProductPrice" placeholder="0.00"> <br />
    <input type="date" id = "DateWhenAdded" name="DateWhenAdded" placeholder="01/01/2001"> <br />
    <input type="submit" name="submit" value="SUBMIT">
</form>
</body>
</html>

However, I have a problem to where I get this error on my browser.

{"error":"Bind parameters must be array if namedPlaceholders parameter is not enabled"}

Does anyone know how to fix this error so I can get my query to run?