Material UI Autocomplete Subselect in ReactJS

I’m using MUI Autocomplete and Formik and I wanted to group this into categories. If it has a sub_account, then get its children.

CODESANDBOX ——>
CLICK HERE

Expected outcome on the UI is something like:

  • Petty Cash

  • Cash In Bank – Bank of America

    • Bank of America – Single Proprietor
    • Bank of America – Corporate Entity
  • Cash

  • CIB – Bank of Vietnam

    • Bank of Vietnam Personal
    • Bank of Vietnam Checking Acc

CODE

export const CashAccountAutocomplete = ({
  field,
  form: { touched, errors, setFieldValue, values },
  disabled,
  ...props
}) => {
  const [inputValue, setInputValue] = useState("");

  const handleChange = (_, newValue, reason) => {
    if (reason === "clear") {
      setFieldValue(field.name, { id: "", name: "" });
      return;
    }
    setFieldValue(field.name, newValue);
  };

  const handleInputChange = (_, newInputValue) => {
    setInputValue(newInputValue);
  };

  const extractSubAccounts = (accounts) => {
    if (!Array.isArray(accounts)) {
      console.error("Invalid accounts data. Expected an array.");
      return [];
    }

    return accounts.flatMap(
      ({ id, name, sub_accounts }) =>
        sub_accounts && sub_accounts.length > 0
          ? extractSubAccounts(sub_accounts) // Recursively extract sub-accounts
          : [{ id, name }] // Include the account if it has no sub-accounts
    );
  };

  const filteredData = extractSubAccounts(accounts);

  return (
    <Autocomplete
      {...field}
      disabled={disabled}
      getOptionLabel={(option) =>
        typeof option === "string" ? option : option?.name || ""
      }
      renderOption={(props, option) => {
        return (
          <li {...props} key={option.id}>
            {option?.name}
          </li>
        );
      }}
      filterOptions={(x) => x}
      options={filteredData || []}
      autoComplete
      includeInputInList
      filterSelectedOptions
      noOptionsText={"No data"}
      onChange={handleChange}
      inputValue={inputValue}
      onInputChange={handleInputChange}
      renderInput={(params) => (
        <TextField
          {...params}
          {...props}
          error={touched[field.name] && errors[field.name] ? true : false}
          helperText={
            touched[field.name] &&
            errors[field.name] &&
            String(errors[field.name].id)
          }
        />
      )}
      fullWidth
    />
  );
};

Fetch with basic authentication works with Postman but not in Javascript

I’m stuck for several hours on a tricky problem.

I would like to access the Windows Device Portal Api (access the Api of a connected Hololens 2 on the same network of the client) but I kept getting a Network Request Failed from Javascript.

The fact is, that request is working well on Postman, but, even when I am stupidly copying the example javascript code from Postman, it still doesn’t work.

The result on Postman:

{
    "ComputerName": "HoloLens2-05",
    "Language": "en-US",
    "OsEdition": "Holographic",
    "OsEditionId": 136,
    "OsVersion": "22621.1272.arm64fre.ni_release_svc_sydney_rel_prod.240403-0940",
    "Platform": "HoloLens 2"
}

Here is my setup:

  • React Native 0.73
  • Targeting Android (simulator or device, they both don’t work)
  • IDE: VSCode on Windows

What I did:

  1. Copying the code from Postman:
var myHeaders = new Headers();
myHeaders.append("Authorization", "Basic base64here");
myHeaders.append("Cookie", "CSRF-Token=csrfTokenHere");

var raw = "";

var requestOptions = {
  method: 'GET',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("https://hololensnetworkip/api/os/info", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));
  1. Set the AndroidManifest in android/src/main:
<uses-permission android:name="android.permission.INTERNET" />
<application
    android:usesCleartextTraffic="true">
  1. Trying the Windows Device Portal suggestion of applying an “auto-” prefix on the login (https://learn.microsoft.com/en-us/windows/uwp/debug-test-perf/device-portal#csrf-protection-and-scripting):
    enter image description here

I know the Windows Device Portal facing issues with not valid certificate status, but why is it working on Postman ? Or why is it working with a call from .Net client ?

Thanks anyway for your hints, I’ll keep searching on my side.

Change button background color when clicking on it (Wix website)

I would like to have the following conditions regarding my button “#button5” on my wix website:

  • Standard color: white;
  • When the user is on the page (contact), the button color will change to red;
  • When the user leaves this page, the button color will return to white.

Can you help me?

I couldn’t do anything because I’m new to the platform

Extract results from networkd3 sankey diagram

I’m new here and this is the second time I’m posting this because the previous post was deleted, I don’t know what the issue was, would be great if you could state the reason before deleting the post.

So I’m trying again…

This question could be quite basic as I’m just starting to use networkd3, so excuse me for that. I tried looking online for help but unfortunately couldn’t find anything. I was wondering if there is any specific way to extract the results of a networkd3 plot.

I’m trying to extract the order of the resulting nodes of the sankey plot in order to use it as an input to other plots but unable to figure out how to extract this information.

I understand that by using iterations=0 I can manually order the nodes but I want to get the ordered nodes so it looks more clean and easier to interpret.

Websocket Connection Failed Django javascript

   I am trying to connect to my websocket from the frontend in javascript

const url = 'wss://chatapprender.onrender.com/${person_id}/';

   I am using django channels for backend

ASGI_urlpatterns = [ path("websocket/<int:id>/", consumers.ChatConsumer.as_asgi()) ]
when the following line is executed it gives this error in the console
WebSocket connection to ‘wss://chatapprender.onrender.com/3/’ failed:
connectToWebsocket @ script.js:71
(anonymous) @ script.js:190

it works on my local 127.0.01:8000 server of django
with this url ws://127.0.0.1:8000/websocket/${person_id}
but when i deploy it it fails to connect

    INSTALLED_APPS = [
        'channels',
        'daphne',
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'chat',
        'accounts',
    ]

    WSGI_APPLICATION = 'mychatproject.wsgi.application'
    ASGI_APPLICATION = 'mychatproject.asgi.application'
**routing.py**
    from django.urls import path
    from . import consumers
    ASGI_urlpatterns = [
        path("websocket/<int:id>/", consumers.ChatConsumer.as_asgi())
    ]
**asgi.py**
    import os
    from chat import routing
    from channels.auth import AuthMiddlewareStack
    from django.core.asgi import get_asgi_application
    from channels.routing import ProtocolTypeRouter, URLRouter
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mychatproject.settings')

    application = ProtocolTypeRouter({
        'http':get_asgi_application(),
        'websocket':AuthMiddlewareStack(URLRouter(routing.ASGI_urlpatterns))
    })
**consumers.py**
    class ChatConsumer(WebsocketConsumer):
        def connect(self):
            self.accept()
            try:
                user_channel = UserChannel.objects.get(user=self.scope.get('user'))
                user_channel.channel_name=self.channel_name
                user_channel.save()
            except:
                user_channel=UserChannel.objects.create(user=self.scope.get('user'),
                                                    channel_name=self.channel_name)
                user_channel.save()
                self.person_id=self.scope.get("url_route").get("kwargs").get("id")

How to show initial value of select component on Material Tailwind React Select Component with options that are mapped

Apparently in the example of using the select component, the options of the Select are not mapped and are singular objects on their own. Currently I am trying to make a select component which shows the outlets that I fetched from the api therefore all the options are mapped from the array that is fetched from the api. The options are managed to be shown however i cant managed to show the initial value hence making the component empty. For purpose of recreating this problem, ive made a temp array of the outlet . Any thoughts or ideas on how to do it

import { Option, Select } from "@material-tailwind/react";
import React, {  useState } from "react";


const outletList = [
  {
    "outletid": 18,
    "storeid": "001",
    "name": "Main Street Store",
    "address": "123 Main Street",
    "storedesc": "This is our flagship store located on Main Street.",
    "status": "Operational",
    
  },
  {
    "outletid": 19,
    "storeid": "002",
    "name": "Downtown Outlet",
    "address": "456 Downtown Avenue",
    "storedesc": "Our outlet in the heart of downtown.",
    "status": "Operational",
    
  },
  {
    "outletid": 20,
    "storeid": "003",
    "name": "Suburbia Mall Store",
    "address": "789 Suburbia Mall",
    "storedesc": "Located in the Suburbia Mall, offering convenient shopping.",
    "status": "Operational",
    
  },
  {
    "outletid": 21,
    "storeid": "004",
    "name": "Beachside Outlet",
    "address": "321 Beachfront Road",
    "storedesc": "Enjoy shopping with a view of the ocean.",
    "status": "Suspended",
    "company": "TheIceCreamBar"
  },
  {
    "outletid": 22,
    "storeid": "005",
    "name": "Industrial Park Store",
    "address": "555 Industrial Avenue",
    "storedesc": "Catering to the needs of businesses in the industrial park.",
    "status": "Operational",
    
  },
  {
    "outletid": 23,
    "storeid": "HQ001",
    "name": "Headquarters",
    "address": "123 HQ Street",
    "storedesc": "Main headquarters of the company.",
    "status": "Operational",
    
  }
]

function SelectOutlet({ user }) {

  const defaultValue = user.length > 0 ? user[0].defaultoutlet : null;
  const defaultOutlet = outletList.find(outlet => outlet.outletid === defaultValue);
  const [value, setValue] = useState(defaultOutlet ? defaultOutlet.name : "");


  


  const handleSelect = (selectedValue) => {
    console.log("event",selectedValue)
    setValue(selectedValue);
  };

  return (
    <div className="my-auto px-2">
      <Select
        size="lg"
        label="Select Outlet"
        selected={value}
        onChange={handleSelect}
        className="text-lg"
        containerProps={{ className: "h-16" }}
      >
        {outletList.map((outlet) => (
          <Option key={outlet.outletid} value={outlet.name}>
            {outlet.storeid} {outlet.name}
          </Option>
        ))}
      </Select>
    </div>
  );
}

export default SelectOutlet;

So the flow of getting the initial outlet is like this, there is a default value received from the user prop. Example, user.defaultoutlet = 18. So i try to match the default outlet to the outletarray to get the corresponding name for it. So far, the object defaultOutlet’s result managed to match its corresponding name however the value object itself only gets undefined.

Notification Provider component causing Hydration errors in NextJS with React Moralis – FCC Pat Collins full stack dev course

I am stuck in lesson 10 and I am unable to progress after the wrapper in my layout.js file in my next app

My Layout.js :

"use client"
import { Inter } from "next/font/google"
import "./globals.css"
import { MoralisProvider } from "react-moralis"
import { NotificationProvider } from "web3uikit"

const inter = Inter({ subsets: ["latin"] })

/* export const metadata = {
    title: "Smart Contract Lottery FCC",
    description: "Generated by create next app",
} */

export default function RootLayout({ children }) {
    return (
        <MoralisProvider initializeOnMount={false}>
            <NotificationProvider>
                <html lang="en">
                    <head>
                        <title>Smart Contract Lottery</title>
                    </head>
                    <body className={inter.className}>{children}</body>
                </html>
            </NotificationProvider>
        </MoralisProvider>
    )
}

My page.js :

"use client"
import { ConnectButton } from "web3uikit"
import LotteryEntrance from "../../components/LotteryEntrance"
export default function Home() {
    return (
        <main className="flex min-h-screen flex-col items-center justify-between p-48">
            <div className="max-w-2xl w-full items-center justify-between font-mono text-5xl">
                Smart Contract Lottery
            </div>
            <div className="flex flex-col gap-y-8 max-w-5xl justify-between items-center text-2xl p-12">
                Decentralized Lottery
                <ConnectButton moralisAuth={false} />
                <LotteryEntrance />
            </div>
        </main>
    )
}

The errors I am getting :

app-index.js:33 Warning: In HTML, <div> cannot be a child of <#document>.
This will cause a hydration error.
    at div
    at O2
    
    Uncaught Error: Hydration failed because the initial UI does not match what was rendered on the server.
    
    An error occurred during hydration. The server HTML was replaced with client content in <#document>.
    
    Uncaught DOMException: Failed to execute 'appendChild' on 'Node': Only one element on document allowed.
    
     Hydration failed because the initial UI does not match what was rendered on the server.
     
     There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.
     
     Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
     
     he above error occurred in the <StrictMode> component:


Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

Uncaught AggregateError
    at flushSyncWorkAcrossRoots_impl 

I tried wrapping up the layout.js component in a separate file and exporting it within the layout.js but then it’s just the same issue being replicated. Am I missing something?

How to create an array of objects in google script using object.map

I am trying to create an array of objects derived from a list of users and have the following line of code:

var usersEmail=group.map((user)=>{eMail : user.email, rOle : user.role});

the ‘:’ in ‘rOle : user.role’ causes an error of unexpected ‘:’ when I try to save the code. If I use this code:

var usersEmail=group.map((user)=>[user.email, user.role]);

I create an array of 2 element array’s, which works but is not as nice as I would like. My final attempt was this:

var usersEmail=group.map((user)=>[{eMail : user.email, rOle : user.role}]);

which creates an array of single element arrays each of which contain the correct object. I feel that what I want to do is entirely possible, but I just don’t have the right structure to do so.

Grateful for any help.

How to Edit or Update contact in react-native-contacts?

I am using react-native-contacts to get a contact list, delete a contact from the list, and add a contact to the list in react-native. So far I have achieved all three functionalities but to edit contact details let’s say its name or number using Contacts.updateContact() is not working.
You can see the below code to see what I am doing –

import React, { useState } from 'react';
import { View, Text, StyleSheet, Image, TextInput, TouchableHighlight, PermissionsAndroid } from 'react-native';
import Contacts from 'react-native-contacts';

const EditContactScreen = ({ route, navigation }) => {
    const { data } = route.params;
    const [firstName, setFirstName] = useState(data.givenName);
    const [lastName, setLastName] = useState(data.familyName);
    const [number, setNumber] = useState(data.phoneNumbers[0].number);
    const [email, setEmail] = useState('');

    console.log('data>>>', JSON.stringify(data, null, 2));

    const editContact = () => {
        PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.WRITE_CONTACTS, {
            title: 'Contacts',
            message: 'This app would like to view your contacts.',
            buttonPositive: 'Please accept bare mortal',
        })
            .then((res) => {
                console.log('Permission: ', res);
                if (res === 'granted') {
                    let updatedContact = {
                        recordID: data.recordID,
                        emailAddresses: [{
                            label: 'work',
                            email: email,
                        }],
                        phoneNumbers: [{
                            label: 'mobile',
                            number: number,
                        }],
                        familyName: lastName,
                        givenName: firstName,
                    };

                    Contacts.updateContact(updatedContact).then(() => {
                        console.log('Contact updated successfully');
                        navigation.goBack();
                    }).catch(error => {
                        console.log('Error updating contact:', error);
                    });
                }
            })
            .catch((error) => {
                console.error('Permission error: ', error);
            });
    };

    const onSubmit = () => {
        editContact();
    };

    return (
        <View style={styles.container}>
            <TextInput
                style={styles.input}
                placeholder="First Name"
                defaultValue={firstName}
                onChangeText={text => setFirstName(text)}
                placeholderTextColor={'#555'}
                cursorColor={'#555'}
            />
            <TextInput
                style={styles.input}
                placeholder="Last Name"
                defaultValue={lastName}
                onChangeText={text => setLastName(text)}
                placeholderTextColor={'#555'}
                cursorColor={'#555'}
            />
            <TextInput
                style={styles.input}
                placeholder="Phone Number"
                defaultValue={number}
                onChangeText={text => setNumber(text)}
                placeholderTextColor={'#555'}
                keyboardType="numeric"
                cursorColor={'#555'}
            />
                <TouchableHighlight
                    style={[styles.button]}
                    onPress={onSubmit}
                >
                    <Text style={styles.btnText}>Save Contact</Text>
                </TouchableHighlight>
        </View>
    );
};
export default EditContactScreen;

I am getting data through route.params from ContactDetail Screen and from that passing recordId to the updatedContact, now whenever I call for editContact() after editing it is giving me error as

Error updating contact: [Error: Invalid recordId or rawContactId]

Even Though as you can see I am passing the recordId correctly but still it is giving me error so what should I do?

Eslint: how to resolve local plugin or rule using rc config file format?

Eslint v8.50, using eslintrc.js config format

I am following custom rule tutorial to create custom rule (which requires a plugin from what I understand), but I’m not able import my local plugin.

Tried following:

  • provide object as per tutorial: object not supported, string required
  • try providing path to my plugin: getting Plugins array cannot includes file paths error
  • create eslint-plugin-example dir with index.js in root of the project (next to eslintrc.js) and provide “eslint-plugin-example” in plugins config: config not found

The only way I managed to make it work is to do npm i ./eslint-plugin-example --save-dev which created symlink in node_modules. This feels too complicated for such simple thing as including local rule/plugin.

Is there any other way to achieve it? (without migrating to flat config)

Is it possible to import a .js file in the index.html (on github) when the .js file is located on another server?

I have a HTML + JS website hosted on github. This website plots data from a .js file. A team member should be able to overwrite this file from time to time, without having acess to the website scripts. Therefore it would be great, if the .js file can be imported although it is located on another server. Is that possible?

Thanks.

I tried to locate the file in another git repository B and set the permament link to the file in the index.html in the other repository A, but it only works when repository B is public (which i do not want).

login using php and ajax

here is my index.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>HTML5 Login Form with validation Example</title>
    <link rel="stylesheet" href="css/style.css" />
  </head>
  <body>
    <div id="login-form-wrap">
      <h2>Login</h2>
      <form id="login-form" action="process.php" method="post">
        <p>
          <input
            type="email"
            id="email"
            name="email"
            placeholder="Email"
            onkeyup = "validateEmail()"
            required
          />
        </p>
        <span id="email-checker"></span>
        <p>
          <input
            type="password"
            id="password"
            name="password"
            placeholder="Password"
            onkeyup = "validatePassword()"
            required
          />
        </p>
        <span id="password-checker"></span>
        <p>
          <input
            type="checkbox"
            id="remember-me"
            name="remember-me"
            value="remember"
          />
          <label for="remember-me"> Remember Me</label>
        </p>
        <p>
          <input type="submit" id="login" value="Login" />
        </p>
      </form>
    </div>
    <script src="js/validateEmail.js"></script>
    <script src="js/validatePass.js"></script>
    <script src="js/ajax.js"></script>
  </body>
</html>

my ajax.js:

$("#login-form").submit(function (e) {
  e.preventDefault(); // Menghentikan pengiriman form default
  var email = $("#email").val();
  var password = $("#password").val();

  $.ajax({
    type: "POST",
    url: "./process.php",
    data: { email: email, password: password },
    success: function (response) {
      if (response === "success") {
        window.location.href = "profile.php";
      } else {
        alert(response);
      }
    },
  });
});

my process.php:

<?php
$emailAwal = "[email protected]";
$passwordAwal = "S@dam123";
$email = $_POST['email'];
$password = $_POST['password'];

function validate($email, $password) {
    global $emailAwal;
    global $passwordAwal;
    if ($emailAwal === $email && $passwordAwal === $password) {
        return true;
    } else {
        return false;
    }
}

if (validate($email, $password)) {
    echo "success";
    exit; 
} else {
    echo 'Invalid email or password';;
    exit; 
}


if i submit the form (whether the email and password correct or wrong) it will redirect to process.php and echo “success” or “invalid email or password” instead of using it as parameter for ajax? it should be alert(response) to index.php if the email and password wrong and redirect to profile if the password and email is correct.

Add button for django formset

I’m starting to use Django 5 and I’m building a web project to organize a Secret Santa gift exchange.

My problem is that when using formsets, they are not dynamic, so I can’t create a variable number of forms at the user’s request.

I have this form:

class ParticipanteForm(forms.ModelForm):
    class Meta:
        model = Participante
        fields = ['nombre', 'email']

ParticipanteFormSet = formset_factory(ParticipanteForm)

This model:

class Participante(models.Model):
    sorteo = models.ForeignKey(Sorteo, related_name='participantes', on_delete=models.CASCADE)
    nombre = models.CharField(max_length=100)
    email = models.EmailField()

And this view where I render the forms and save the data:


def crear_sorteo(request):
    sorteo_form = SorteoForm(request.POST or None)
    ParticipanteFormSet = formset_factory(ParticipanteForm, extra=3)
    participante_formset = ParticipanteFormSet(request.POST or None)
    
    context = {
        'sorteo_form': sorteo_form,
        'participante_formset': participante_formset,
    }
    
    if request.method == 'POST':
        if sorteo_form.is_valid():
            sorteo = sorteo_form.save()  # Save the draw first
            if participante_formset.is_valid():
                for participante_form in participante_formset:
                    participante = participante_form.save(commit=False)
                    participante.sorteo = sorteo  # Assign the draw to the participant
                    participante.save()
                return render(request, 'sorteo_realizado.html')
    
    return render(request, 'crear_sorteo.html', context)

As you can see, ParticipanteFormSet = formset_factory(ParticipanteForm, extra=3) depending on the number of extra you specify, that will be the number of forms that will be created. But I would like in the template:

<body>
    <form action="" method="post">
        {% csrf_token %}
        {{ sorteo_form }}
        {{ participante_formset.management_data }} 
        {{ participante_formset.as_p }}
        <input type="submit" value="Realizar sorteo">
    </form>
</body>

there to be a button to add a participant so the user can enter as many users as they want with a minimum of 3 participants.

I’ve tried to make a button that posts and upon receiving it, the number of extra updates to +1, but the page reloads and the data is lost. If anyone knows how to achieve this, it would be very helpful, thanks in advance.

remove class to child element with jquery

I´m trying to do a logic, that when user focus in text div, show a action button to mark as read a message. To do this.

First i´m getting all messages in my view, and i add a block with button:

<div class="row flex-row align-items-center block_message_{{$message->id}}">
                                <div class="col-md-9">
                                    @if ($message->publisher_comments != "" || $message->publisher_comments != null)
                                        <span>{{ $message->publisher_comments }}</span>
                                    @else
                                        <span>{{ $message->client_comments }}</span>
                                    @endif
                                </div>
                                <div class="col-md-2 d-none" id="block_mark_read_{{$message->id}}">
                                    <button class="read-more-info-icon modal-right">
                                        <i class="fa fa-eye fa-2x" aria-hidden="true"></i>
                                        <span class="hidden-info">{{ trans('placeholders.mark_read') }}</span>
                                    </button>
                                </div>
                            </div>

And with jquery, i´m trying to use focus event in my parent div, to show icon in my child div, but my icon not show it. and i don´t getting any message or error.

<script>
    let index = 0;
    $(".block_message div").focus(function(event) {
        $(this).removeClass('d-none');
    });
    let block_messages = $(".block_message").map(function() {
        index++;

        let block = $('.block_message_'+index).find('#block_mark_read_'+index);
        

        /*$(this).find("#block_mark_read_"+index).addEventListener('focus', function(){
            $(this).removeClass('d-none');
        })*/

        block.addEventListener('focus', function(){
            console.log("entro");
        })

    })
    
</script>

My question it´s, how i can to do, to show icon beside my div and add action to mark read

Thanks for readme, help and sorry for my bad english