AngularJs template request and $compile with ng-controller

This is a very old system, that we’re not in a spot to update to something modern… just wanted to get that out there.

I’m working on a project that is based on Angular 1.5. I’ve been tasked with allowing people to download a PDF version of all the pages/tabs visible to them on a website. I’m trying to use the built in tools of AngularJS but I’m hitting issues when a page has ng-model binds.

I have a download content page/tab where folks can download all the other pages. Defined as:

registrationModule.controller("dataDownload", function ($scope, $http, $q, $routeParams,
$location, viewModelHelper, $rootScope, $compile, $timeout, $templateRequest, $sce, $cookies) {

$scope.isLoading = true;
$scope.buttonsDisabled = false;
$scope.error = false;

var initPage = function () {
    $scope.isLoading = false;
};

initPage();

$scope.downloadContent = function (httpResponse) {

    var blob = new Blob([httpResponse.data], { type: "application/pdf" });
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);

    const fn = httpResponse.headers()['content-disposition'];
    if (fn) {
        link.download = fn.slice(fn.indexOf("=") + 1);
    } else {
        link.download = 'download.pdf';
    }

    link.click();
}

$scope.prepareContent = function (templateUrl, stringElement, pdfName) {
    $templateRequest(templateUrl).then(function (template) {
        var angularElement = angular.element(stringElement);
        
        $compile(angularElement.html(template).contents())($scope);
        

        $timeout(function () {

            const payload = {
                htmlContent: angularElement.html(),
                pdfName: pdfName
            };

            viewModelHelper.apiConfigPost('api/content-downloads/generate-pdf', payload, { responseType: "arraybuffer" },
                // creates PDF (THIS WORKS)
            );
        });
    });
}

$scope.downloadBio = function () {
    $scope.buttonsDisabled = true;
    $scope.error = false;

    var templateUrl = $sce.getTrustedResourceUrl('/App/Registration/Views/Bio.html');
    var stringElement = '<div data-bio></div>';
    $scope.prepareContent(templateUrl, stringElement, 'Bio');
};
});

The BIO view.html is define like:

<div class="row registrationInnerContent" ng-controller="bioModel">

    <input type="text" class="form-control full-width" ng-model="bio.Nickname">
    ... more ng-model binds ...
</div>

The BIO js model is defined like so:

registrationModule.controller("bioModel", function ($scope, registrationService, $http, $q, $routeParams, $window, $location,
    viewModelHelper, $rootScope, $cookies, toastrFactory, focus, $uibModal) {

    $scope.bio = null;
    
    ... other items not relevant ....

    var getBio= function () {
        viewModelHelper.apiGet('api/getbio/' + $rootScope.custId, null,
            function (result) {
                $scope.bio = result.data;              
            });
    }
    
    getBio();
});

How can I get my data download controller to successfully fill in the ng-model pieces of the BIO.html when using the $compile (and other) functions?

Best Practice for Setting MSAL Access Token

I’ve got a React application that is registered with a SPA configuration in Entra. Per the MSAL documentation, the default cache location is set to sessionStorage, this can be set to localStorage for reasons described here and discussed here, but I don’t do this in my MSAL configuration. Instead, in my handleRedirectPromise, I set the item key “accessToken” in my local storage to the token I receive from my MSAL auth callback. Then, using Axios Interceptors, I set the Authorization Header to the token stored in my local storage as so:

axios.interceptors.request.use(function (config) {
   config.headers.Authorization = localStorage.getItem('accessToken')
   return config;
});

I do this because without it, every time I reload the page, the authorization header that I originally was setting in my handleRedirectPromise via axios.defaults.headers.common[AuthConstants.AUTH_HEADER] assignment, would be erased and the value would be undefined.

So I tried accessing the token value from the cache location, but the token would be stored in an object with the key of the homeAccountId appended to other values which could be different every time a user logged in. For this reason, I don’t even bother changing my cacheLocation to localStorage in my MSAL configuration. Perhaps there’s a way to name the cache key in the MSAL configuration?

Anyways, doing it that way resulted in some janky code, so I tried the next option available, acquireTokenSilent. To be fair, I’m not sure how it should be organized into my code base as several demo examples have different implementations, but hardly any explanation for how the token is added to the header without either providing an existing logged in account or callback. But, as I’ve stated above, the page reload will erase the header, plus even if it weren’t erased, I’d still be relying on some user information to be stored because how else will I know if there is an active account if I don’t call the following during my handleRedirectPromise response:

msalInstance.setActiveAccount = res.account

So that I could run the following code before every HTTP request, found in this demo:

  if (!accessToken) {
      const account = instance.getActiveAccount();
      if (!account) {
          throw Error("No active account! Verify a user has been signed in and setActiveAccount has been called.");
      }

      const response = await instance.acquireTokenSilent({
          ...loginRequest,
          account: account
      });
      accessToken = response.accessToken;
  }

And I suppose I could use ssoSilent without any supplemental information as stated here to get and add my token to the header, but this implementation has a different purpose from what I’m trying to resolve.

As the title suggests, I’m concerned if what I’ve got working is best practice, or, more specifically, has some security risks that I should be considering. I appreciate any suggestions and advice you may have to offer. Thanks!

Rails Admin UI Not Working Properly with Custom JS

I recently added a custom action that requires some custom JavaScript. To do so I added app/assets/javascripts/rails_admin/ui.js

//= require ../google_places_autocomplete.js
//= require ../google_places_autocomplete_validation.js

My custom action works correctly, but when I go to my form to create a new instance the UI is not correct. There are no console errors. My custom CK Editor doesn’t show on the content field, the date picker doesn’t work, and the Author drop down is displayed differently.

incorrect_admin_ui

If I remove my custom file at app/assets/javascripts/rails_admin/ui.js everything works as expected (except for my custom action, of course).

expected_admin_ui

Why is adding the ui.js file causing this, and how can I get around it?

Design Dynamic “Panel” component [closed]

  1. The panel shows one of many “views” depending on it’s state.
  2. Each view presents information and may interact with user
  3. Any of the views can alter the “panel” state, trigger events
  4. Panel responds to state change and events to possibly swap the current view with another
  5. Implement using using only JavaScript/HTML/CSS – no frameworks

Ways I know of that might accomplish this:

  1. js: directly manipulate the DOM
  2. CSS, z-order, hidden/visible, etc.

An example would be a “login” panel:

  1. state:not-logged-in: the usual username/password and login button
  2. state:is-logged-in: “you are logged in as USERNAME”, logout button

My impression so far is that CSS is the more elegant way to do this, however, my knowledge of CSS pales in comparison to JavaScript. I just need to get this working quickly without watching a thousand, many outdated, videos and articles about CSS.

Remove div inside parent div in jquery object only

I have a divs inside parent div:

<div id="parent">
  <div id="child">some content1</div>
  <div id="child">some content1</div>
</div> 

I get the parent div using jquery:

var allDivs= $("#parent").html();

I want to remove child divs from this parent, how i can do this? child divs should be deleted from jquery object but not from dom, is it possible?

How to integrate startbootstrap into a react component?

I’m working on a React component that incorporates a StartBootstrap template from this link.Here is the full picture of an ideal page:

enter image description here

After downloading the template and opening the index.html file, I see the HTML structure looks like this:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
        <meta name="description" content="" />
        <meta name="author" content="" />
        <title>Dashboard - SB Admin</title>
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/style.min.css" rel="stylesheet" />
        <link href="css/styles.css" rel="stylesheet" />
        <script src="https://use.fontawesome.com/releases/v6.3.0/js/all.js" crossorigin="anonymous"></script>
    </head>
    <body class="sb-nav-fixed">
        <!-- All the dashborad elements in this page -->
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
        <script src="js/scripts.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js" crossorigin="anonymous"></script>
        <script src="assets/demo/chart-area-demo.js"></script>
        <script src="assets/demo/chart-bar-demo.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/simple-datatables.min.js" crossorigin="anonymous"></script>
        <script src="js/datatables-simple-demo.js"></script>
    </body>
</html>

My main challenge lies in organizing the CSS, JavaScript, and assets within my React project to ensure the template renders correctly. Below is how I structured the assets:

enter image description here

As shown in the image, I’ve included the CSS and JS files like this:

<link rel="stylesheet" href="%PUBLIC_URL%/start-bootstrap-assets/css/style.css" />
<script src="%PUBLIC_URL%/start-bootstrap-assets/js/script.js"></script>

However, despite my efforts, the HTML page appears broken as below picture:
enter image description here

So, i think, still some js are not properly addressed in my project.

Can anyone guide me on how to properly set up these assets in my React app to achieve the desired layout?

Link to full code in Github to reproduce this problem!

Issue with Drag and Drop Not Adding Tasks to Empty Containers in DnD Kit

I’m implementing a drag-and-drop feature in a project management board using dnd-kit. The functionality works well when tasks are dragged between containers that already have tasks. However, I’m encountering an issue when trying to drag a task into an empty container.

Currently, the drag-and-drop functionality does not seem to add the task to an empty container. Here’s my current onDragEndHandle function with helper comments:

  function onDragEndHandle(event: any) {
    const { active, over } = event;

    // Return if no change in position
    if (!over || active.id === over.id) return;

    const activeTask = tasks.find((i) => i.id === active.id);
    const overTask = tasks.find((i) => i.id === over.id);

    setTasks((tasks) => {
      // If the task is dragged to a different container
      if (
        activeTask &&
        overTask &&
        activeTask.category_task_id !== overTask.category_task_id
      ) {
        // Update the category_task_id for the task to reflect the new container
        activeTask.category_task_id = overTask.category_task_id;
      }

      // Find positions of active and over tasks
      const oldPos = tasks.findIndex((i) => i.id === active.id);
      const newPos = tasks.findIndex((i) => i.id === over.id);

      // Reorder tasks based on the new positions
      return arrayMove(tasks, oldPos, newPos);
    });
  }

Sign In failed in for Javascript Email, FB login

I am working on a Javascript-based website. I integrated Firebase Google and Facebook SignIn. Everything was working fine. After 3 months, when I checked again. Firebase Google and Facebook Sign-in starts failing. I do not understand what happened. I checked everything, firebaseConfig, project_id, and other things. Everything is okay. I cleared the cache and ran it on different browsers, however, it still failed.

One error that I get in the beginning is related with /__/firebase/init.json. “404(not found)”. However, after that my browser shows the Google SignIn page and I signs In. But then in “onAuthStateChanged(auth, async (user) => {” it says, user is not Signed In.

import { getAuth, FacebookAuthProvider, GoogleAuthProvider, signInWithRedirect, 
  getRedirectResult, onAuthStateChanged, signOut } from "https://www.gstatic.com/firebasejs/10.14.1//firebase-auth.js";

//Google SignIn button click
googleSignIn.addEventListener('click', async()=>{

  console.log('Google button clicked');
  await signInWithRedirect(auth, googleProvider);

  getRedirectResult(auth)
  .then((result) => {
    // This gives you a Google Access Token. You can use it to access Google APIs.
    const credential = GoogleAuthProvider.credentialFromResult(result);
    const token = credential.accessToken;
    
    console.log("token is");
    // The signed-in user info.
    const user = result.user;

    createFireStoreUser(user.uid, user.displayName);

    // IdP data available using getAdditionalUserInfo(result)
    // ...
  }).catch((error) => {
    // Handle Errors here.
    console.log("error is");
    const errorCode = error.code;
    const errorMessage = error.message;
    // The email of the user's account used.
    const email = error.customData.email;
    // The AuthCredential type that was used.
    const credential = GoogleAuthProvider.credentialFromError(error);
    // ...
  });

});

Redux is not updating the state, and confused how to do this properly

I am working with React on the frontend and trying to use Redux with createAsyncThunk to make a api call.
It fetches the data correctly , and can see it with console.log within the ‘extraReducer’ property within the ‘slice’
But to update the state and retrieve the data to the component returns a undefined. The weird thing is that it worked at first but suddenly it doesnt return the updated state

store.js

import { configureStore, applyMiddleware } from "@reduxjs/toolkit"
// import { getAvailableLocations } from "./middleware/locationThunk"
import userSlice from "./features/users/userSlice.jsx"

export const store = configureStore({
    reducer: {
        users: userSlice
    },
    devTools: process.env.NODE_ENV === 'development',
    trace: true
})

util. js

export const initialUserState = {
    first_name: '',
    last_name: '',
    email: '',
    password: '',
    location: '',
    phone_number: '',
    region: '',
    data_of_birth: '',
    gender: '',
    conversion: '',
    cityId: null,
    city_list: [],
    state_id: null,
    state_list: [],
    // status: 'idle', // | 'loading' | 'succeeded' | 'failed'
    // error: null
}

userSlice.js

import initialUserState from './util'

export const getAvailableLocations = createAsyncThunk(
        '/api/getLocation', 
        async (id) => {
            try {
                let getCities = []
                const getStates = await GetState(countryid) // countryid
                if(id) getCities = await GetCity(countryid, id)
                    return { getStates, getCities}
            } catch (err) {
                console.log({'userSlice.js: - nr.19 - getLocation': err})
                return err.message
            }
        })

const userSlice = createSlice({
    name: 'users',
    initialState:{user: initialUserState, status: 'idle', error: null},
    reducers: {
        updateUser: {
            modify(state, action) {
                // state.user.users
                console.log({state, action})
            }
        },
        createUser: {createUser(state, action){
            console.log({state, action})
                state.user.users.push(action.payload)
            },
        },
        updateProfile(state, action){
            console.log({state, action})
        },
    },
    extraReducers: builder => {
        builder
            .addCase(getAvailableLocations.fulfilled, (state, action) => { 
                state.status = 'success'

                let stateList = action.payload.getStates
                let optionStateList = stateList.map((state) => ({
                    label: state.name,
                    value: state.id
                }))

                let cityList = action.payload.getCities
                let optionCitiesList = cityList.map((city) => ({
                    label: city.name,
                    value: city.id
                }))

                // console.log({reconstructedStateList: optionStateList, reconstructedCitiesList: optionCitiesList})

                // state.user.state_list.push(optionStateList)
                // state.user.city_list.push(optionCitiesList)
                // state.user.state_list.concat({...optionStateList})
                state.user.state_list = {...optionStateList}
                state.user.city_list = {...optionCitiesList}
                console.log({updated_state: state.user.state_list})

                //return action.payload
                // console.log({updated_StateList: state.user.state_list, updated_CityList:state.user.city_list})
            })
            .addCase(getAvailableLocations.pending, (state, action) => {
                state.status = 'loading'
            })            
            .addCase(getAvailableLocations.rejected, (state, action)=> {
                state.status = 'failed'
                state.error = action.error
            })
    },
    selectors: {
        selectStateList: (state) => state.user.state_list
    }
    }
)

const{ selectStateList } = userSlice.selectors

// Extract the action creators object and the reducer
const { actions, reducer } = userSlice
// Extract and export each action creator by name
export {actions, selectStateList} // { createUser, updateUser, editLo }
// Export the reducer, either as a default or named export
export default reducer

component :

import { useSelector, useDispatch } from 'react-redux'
import { getAvailableLocations, selectStateList } from '../../../store/features/users/userSlice.jsx' //, getUserProfile


export const ProfileTabInterface = () => {

const reduxDispatch = useDispatch()
const user = useSelector((state) => state.user)

console.log({reduxUser: user})

    console.log({reduxStateList: selectStateList})

    if(user?.state_list){
        console.log('state list came through?')
        const {city_list, state_list} = user
        const stateList = state_list
        const cityList = city_list
        console.log({isEmptyStateList: stateList , isEmptyCityList: cityList})
    }

    let stateSelected = {id:2612}
    let userFinalFormData = {
        email: '',
        phone_number: ''
    }

    const getLocations = async (id) => {
        await reduxDispatch(getAvailableLocations(id))
        // await reduxDispatch(getAvailableLocations(id)).unwrap()
    }

    useEffect(() => { 
        // console.log({stateSelected})
        getLocations(stateSelected.id)
        // reduxDispatch(getAvailableLocations(stateSelected.id))
        // reduxDispatch(getUserProfile())

        if(user){        
            const { email, phone_number } = user

            userFinalFormData.email = email
            userFinalFormData.phone_number = phone_number
            Object.entries(userFinalFormData).map(([key, value]) => {
                setEnteredInput((prevValues) => ({
                    ...prevValues,
                    [key]: value
                }))
            })
        }
    }, [])
    
    const handleGeneralUserInput = (identifier, value) => {
        setEnteredInput((prevValues) => ({
            ...prevValues,
            [identifier]: value
        }))
        const updateUserForm = {[identifier]: value}
        dispatch({type: 'SET_GENERAL_USER_DATA', payload: updateUserForm})
    }

    const handleStatelUserInput = (identifier, value) => {
        console.log({stateEvent: value, identifier})
        if(!stateList) return
        stateSelected = stateList.find((state) => state.id == Number(value))          
        handleGeneralUserInput('state_id', stateSelected.id)        
        handleGeneralUserInput(identifier, stateSelected.name)
        reduxDispatch(getAvailableLocations(stateSelected.id))
    }

    const typeText = 'text'
    const typePhone = 'tel'
    const typeLocation = 'location'
    const InterfaceConfiguration = {
        buttonname: 'Save Changes',
        setItems : [
            { name: 'Email', id: 'email', type: typeText, placeholder: 'email', value: enteredInput?.email, error: errors.email, invalid: enteredInputIsInvalid.email, autoComplete: 'email', required:true, onChange: (e) => handleGeneralUserInput('email', e.target.value), onBlur : (e) => inputBlurHandle('email', e.target.value, setEnteredInputIsInvalid)},
            { name: 'PhoneNumber', id: 'phone_number', type: typePhone, placeholder: 'phone number', value: enteredInput?.phone_number, error: errors.phone_number, invalid: enteredInputIsInvalid.phone_number, required:true, onChange: (value) => handleGeneralUserInput('phone_number', value), onBlur : (e) => inputBlurHandle('phone_number', e.target.value, setEnteredInputIsInvalid)},
            { name: 'Location', id: 'location', type: typeLocation, value: enteredInput?.city, cityId: enteredInput?.city_id, stateId: enteredInput?.state_id, error: errors?.location, invalid: enteredInputIsInvalid?.city,
                required:true , onChangeState: (e) => handleStatelUserInput('state', e.target.value), onChangeCity: (e) => handleCitylUserInput('city', e.target.value), onBlur : (e) => inputBlurHandle('city', e.target.value, setEnteredInputIsInvalid)},
            ]
    }

    console.log({enteredInputProfileTab: enteredInput})

    return(
        <>
            <CreateFormInterface array={InterfaceConfiguration.setItems} />
        </>
    )

App.js

import { Provider } from 'react-redux'
import { store } from './store/index.js'

function App() {

  const router = createBrowserRouter([
    { 
      path: '/', 
      element: <RootLayout />,
      errorElement: <ErrorPage />,
      id: 'root',
      loader: tokenLoader,
      children: [
        { path: '/', element: <HomePage /> },
        { path: '/sign-up', element: <SignUpPage />, loader: SignUpLoader },
        { path: '/work', element: <LoginPage /> },
        { path: '/calendar', element: <CalendarPage />, loader: CalendarLoader},
        { path: '/subscribe', element: <OrderPage />},
        { path: '/payment', element: <PaymentPage />},
        { path: '/dashboard/*', element: <DashboardPage />}, //,  loader: UserLoader
        { path: '/contact', element: <ContactPage />},
      ]  
    }
  ])

  return (

<Provider store={store}>

    <ReactQueryClientProvider>
        <UserFormContextProvider>
          <RouterProvider router={router} ></RouterProvider>
      
        </UserFormContextProvider>
    </ReactQueryClientProvider>
    </Provider>
  )
}

export default App

I have tried using the return ‘type’ to return the updated state, and tried returnnig the payload but not getting the results that I wanted still cannot get the data within the state (updated)

I have a question about “axios.” It’s a question about formdata

I received a reply saying that the applyGroup function does not return anything, so no properties were called at that time.
If so, will it be sent if it is not imported from other components and is used from the same component?

This is a question I wrote before.

I’m using “axios” and when I sent it, I got an error then, so I checked it on the console and there was nothing in the data

import { BASE_URL, accessToken } from "../../Apis/Common";

const handleSubmit = async (e) => {
    e.preventDefault();
    switch (buttonStatus) {
      case "apply":
        if (modalData.day.length === 0 || modalData.role === '' || !linkButtonDisable) {
          alert('all typing');
          if (modalData.day.length === 0) {
            setIsDayValid(false);
          } else {
            setIsDayValid(true);
          }
          if (modalData.role === '') {
            setIsSelectRoldValid(false);
          } else {
            setIsSelectRoldValid(true);
          }
          if (!linkButtonDisable) {
            setIsPortfolioTextValid(false);
          } else {
            setIsPortfolioTextValid(true);
          }
        } else {
          alert('send');
          setIsDayValid(true);  
          setIsSelectRoldValid(true); 

          try {
            const formData = new FormData();
            formData.append("name", modalData.name);
            formData.append("email", modalData.email);
            formData.append("role", modalData.role);
            formData.append("reason", modalData.reason);
            formData.append("portfolioLink", modalData.portfolioLink);
            formData.append("date", modalData.date);
            formData.append("introduce", modalData.introduce);
            formData.append("freeEntry", modalData.freeEntry);
            formData.append("day", modalData.day);
            formData.append("language", modalData.language);

            const response = await axios.post(
              `${BASE_URL}/post/${groupId}/apply`,
              formData
            );
            
            alert("done");
            
            onClose();
          } catch (error) {
            
            console.error(
              "fail:",
              error.response ? error.response.data : error.message
            );
            alert("fail. try");

          }
        }
        break;
      case "done":
        alert("done");
        onClose();
        break;
      case "reject":
        alert("reject");
        onClose();
        break;
    }
  };

If I connect it directly to formdata in this way, will it become a post?

And I need to get the groupId from the backend but I don’t know how to get it..

const groupResponse = await axios.get(`${BASE_URL}/post/${groupId}`);
const groupId = groupResponse.data.groupId;

I was going to call it like this, but it didn’t reset.

Axios is so hard…

Dynamic Form Fields Based on Selected Category in React Native

I am developing a React Native application where I need to create a form that displays different fields based on the user’s selected category. I am using Formik for form handling and want to conditionally render form fields depending on the category selected from a dropdown.

I have set up a basic form using Formik, and I have a dropdown (or picker) that allows the user to select a category. However, I’m struggling with the logic to conditionally render different sets of form fields based on the selected category.

Here’s a snippet of my current implementation:

`

import React, { useContext, useCallback } from "react";
import { ScrollView } from "react-native";
import { Formik } from "formik";
import InputField from "./InputForm";
import { useNavigation } from "@react-navigation/native";
import { DispatchContext, StateContext } from "../../store";
import SubmitButton from "../Button/SubmitButton";
import FormPicker from "./FormPicker";
import { convertToFormData } from "../../utlis/FormDataUtils";
import FormValidation from "./FormValidation";
import { FormStyles } from "./FormStyles";
import CategoryFormFields from "./CategoryFormFields";
import { Services } from "../../services/DirectoryServices";

const Form = () => {
  const dispatch = useContext(DispatchContext);
  const { user, address } = useContext(StateContext);
  const navigation = useNavigation();

  // Getting userId and initializing form values
  const userId = user?.session?.data?.attributes?.id || "Null";
  const initialValues = {
    country: "",
    state: "",
    name: "",
    description: "",
    address: address,
    contact: "",
    email: "",
    tags: "",
    activities: "",
    pics: [],
    hours: "",
    amenities: "",
    prices: "",
    seat: "",
    details: "",
    language: "",
    profilePic: "",
    expertise: "",
    experience: "",
    availability: "",
    licenses: "",
    certificate: "",
    unit: "",
    user_id: userId,
    category: "",
  };

  // Handling location selection
  const handleLocationSelect = useCallback(
    (selectedAddress) => {
      dispatch({
        type: "UPDATE_LOCATION",
        payload: selectedAddress,
      });
    },
    [dispatch]
  );

  // Submitting the form data
  const onSubmit = useCallback(
    (values, { resetForm }) => {
      try {
        const formData = convertToFormData(values);
        Services("post", null, formData)
          .then((res) => {
            dispatch({
              type: "SNACKBAR_OPEN",
              payload: {
                isNotify: true,
                severity: "success",
                message: "Submission Successful!",
              },
            });
            navigation.goBack();
            resetForm();
          })
          .catch((err) => {
            console.error("Submission Error:", err);
            dispatch({
              type: "SNACKBAR_OPEN",
              payload: {
                isNotify: true,
                severity: "error",
                message: "Submission Failed!",
              },
            });
          });
      } catch (err) {
        console.error("Error during form submission:", err);
      }
    },
    [dispatch, navigation]
  );

  return (
    <Formik
      initialValues={initialValues}
      validationSchema={FormValidation}
      onSubmit={onSubmit}
    >
      {({
        handleChange,
        handleBlur,
        handleSubmit,
        values,
        errors,
        touched,
        setFieldValue,
      }) => (
        <ScrollView style={FormStyles.container}>
          <FormPicker values={values} handleChange={handleChange} />
          <CategoryFormFields
            values={values}
            handleChange={handleChange}
            handleBlur={handleBlur}
            errors={errors}
            touched={touched}
            setFieldValue={setFieldValue}
          />
          {/* Input fields for Name, Contact, Description, and Email */}
          <InputField
            label="Name *"
            placeholder="Enter name"
            onChangeText={handleChange("name")}
            onBlur={handleBlur("name")}
            value={values.name}
            error={errors.name}
            touched={touched.name}
          />
          <InputField
            label="Contact *"
            placeholder="Enter contact"
            onChangeText={handleChange("contact")}
            onBlur={handleBlur("contact")}
            value={values.contact}
            error={errors.contact}
            touched={touched.contact}
          />
          <InputField
            label="Description *"
            placeholder="Enter description"
            onChangeText={handleChange("description")}
            onBlur={handleBlur("description")}
            value={values.description}
            error={errors.description}
            touched={touched.description}
          />
          <InputField
            label="Email *"
            placeholder="Enter email"
            onChangeText={handleChange("email")}
            onBlur={handleBlur("email")}
            value={values.email}
            error={errors.email}
            touched={touched.email}
          />
          {/* Address Input with Location Selection */}
          <InputField
            label="Address *"
            placeholder="Enter address"
            onChangeText={handleChange("address")}
            onBlur={handleBlur("address")}
            value={values.address}
            error={errors.address}
            touched={touched.address}
            onLocationPress={() => {
              navigation.navigate("MapOverview", {
                onSelectLocation: (lat, long, selectedAddress) => {
                  handleLocationSelect(selectedAddress);
                  setFieldValue("address", selectedAddress);
                },
              });
            }}
          />
          <SubmitButton onPress={handleSubmit} />
        </ScrollView>
      )}
    </Formik>
  );
};

export default Form;
import React from "react";
import { Text } from "react-native";
import CategoryPicker from "../CategoryPicker/CategoryPicker";
import InputField from "./InputForm";
import { FormStyles } from "./FormStyles";
import MultipleImageSelector from "../ImagePicker/MultipleImageSelector";
import SingleImageSelector from "../ImagePicker/SingleImageSelector";

const CategoryFormFields = ({
  values,
  handleChange,
  handleBlur,
  errors,
  touched,
  setFieldValue,
}) => {
  return (
    <>
      <CategoryPicker
        values={values}
        handleChange={handleChange}
        error={errors.category}
      />
      {errors.category && (
        <Text style={FormStyles.error}>{errors.category}</Text>
      )}

      {values.category === "HomeStay" && (
        <>
          <InputField
            label="Rate *"
            placeholder="Rate"
            onChangeText={handleChange("rate")}
            onBlur={handleBlur("rate")}
            value={values.rate}
            error={errors.rate}
            touched={touched.rate}
          />
          <InputField
            label="Activities *"
            placeholder="Activities"
            multiline
            onChangeText={handleChange("activities")}
            onBlur={handleBlur("activities")}
            value={values.activities}
            error={errors.activities}
            touched={touched.activities}
          />
          <InputField
            label="Amenities *"
            placeholder="Amenities"
            onChangeText={handleChange("amenities")}
            onBlur={handleBlur("amenities")}
            value={values.amenities}
            error={errors.amenities}
            touched={touched.amenities}
          />
          <MultipleImageSelector
            label="Pics *"
            onImageSelected={(images) => {
              console.log("Selected images:", images);
              setFieldValue("pics", images);
            }}
            value={values.pics.length > 0 ? "Images Selected" : ""}
          />
        </>
      )}

      {values.category === "CarRental" && (
        <>
          <InputField
            label="Vehicle Detail *"
            placeholder="Details"
            onChangeText={handleChange("details")}
            onBlur={handleBlur("details")}
            value={values.details}
            error={errors.details}
            touched={touched.details}
          />
          <InputField
            label="Seat *"
            placeholder="Seat"
            onChangeText={handleChange("seat")}
            onBlur={handleBlur("seat")}
            value={values.seat}
            error={errors.seat}
            touched={touched.seat}
          />
          <InputField
            label="Rate *"
            placeholder="Rate"
            onChangeText={handleChange("rate")}
            onBlur={handleBlur("rate")}
            value={values.rate}
            error={errors.rate}
            touched={touched.rate}
          />
          <InputField
            label="Unit *"
            placeholder="Unit"
            onChangeText={handleChange("unit")}
            onBlur={handleBlur("unit")}
            value={values.unit}
            error={errors.unit}
            touched={touched.unit}
          />
          <MultipleImageSelector
            label="Pics *"
            onImageSelected={(images) => {
              console.log("Selected images:", images);
              setFieldValue("pics", images);
            }}
            value={values.pics.length > 0 ? "Images Selected" : ""}
          />
        </>
      )}

      {values.category === "Cafe" && (
        <>
          <InputField
            label="Add Tags *"
            placeholder="Add Tags"
            onChangeText={handleChange("tags")}
            onBlur={handleBlur("tags")}
            value={values.tags}
            error={errors.tags}
            touched={touched.tags}
          />
          <InputField
            label="Prices *"
            placeholder="Prices"
            onChangeText={handleChange("prices")}
            onBlur={handleBlur("prices")}
            value={values.prices}
            error={errors.prices}
            keyboardType="numeric"
            touched={touched.prices}
          />
          <MultipleImageSelector
            label="Pics *"
            onImageSelected={(images) => {
              console.log("Selected images:", images);
              setFieldValue("pics", images);
            }}
            value={values.pics.length > 0 ? "Images Selected" : ""}
          />
          <InputField
            label="Operational Hours *"
            placeholder="Eg: 09:00 AM - 09:00 PM"
            onChangeText={handleChange("hours")}
            onBlur={handleBlur("hours")}
            value={values.hours}
            error={errors.hours}
            touched={touched.hours}
          />
        </>
      )}

      {values.category === "Restaurant" && (
        <>
          <InputField
            label="Add Tags *"
            placeholder="Add Tags"
            onChangeText={handleChange("tags")}
            onBlur={handleBlur("tags")}
            value={values.tags}
            error={errors.tags}
            touched={touched.tags}
          />
          <InputField
            label="Prices *"
            placeholder="Prices"
            onChangeText={handleChange("prices")}
            onBlur={handleBlur("prices")}
            value={values.prices}
            error={errors.prices}
            keyboardType="numeric"
            touched={touched.prices}
          />
          <MultipleImageSelector
            label="Pics *"
            onImageSelected={(images) => {
              console.log("Selected images:", images);
              setFieldValue("pics", images);
            }}
            value={values.pics.length > 0 ? "Images Selected" : ""}
          />
          <InputField
            label="Operational Hours *"
            placeholder="Eg: 09:00 AM - 09:00 PM"
            onChangeText={handleChange("hours")}
            onBlur={handleBlur("hours")}
            value={values.hours}
            error={errors.hours}
            touched={touched.hours}
          />
        </>
      )}

      {values.category === "Local Guide" && (
        <>
          <InputField
            label="Language *"
            placeholder="Language"
            onChangeText={handleChange("language")}
            onBlur={handleBlur("language")}
            value={values.language}
            error={errors.language}
            touched={touched.language}
          />
          <InputField
            label="Area of Expertise *"
            placeholder="Expertise"
            onChangeText={handleChange("expertise")}
            onBlur={handleBlur("expertise")}
            value={values.expertise}
            error={errors.expertise}
            touched={touched.expertise}
          />
          <InputField
            label="Experience *"
            placeholder="Experience"
            onChangeText={handleChange("experience")}
            onBlur={handleBlur("experience")}
            value={values.experience}
            error={errors.experience}
            touched={touched.experience}
          />
          <InputField
            label="Availability *"
            placeholder="Availability"
            onChangeText={handleChange("availability")}
            onBlur={handleBlur("availability")}
            value={values.availability}
            error={errors.availability}
            touched={touched.availability}
          />
          <SingleImageSelector
            label="ProfilePic *"
            onImageSelected={(images) => {
              console.log("Selected images:", images);
              setFieldValue("profilePic", images);
            }}
            value={values.pics.length > 0 ? "Images Selected" : ""}
          />
          <SingleImageSelector
            label="License *"
            onImageSelected={(images) => {
              console.log("Selected images:", images);
              setFieldValue("license", images);
            }}
            value={values.pics.length > 0 ? "Images Selected" : ""}
          />
          <SingleImageSelector
            label="Certificate *"
            onImageSelected={(images) => {
              console.log("Selected images:", images);
              setFieldValue("certificate", images);
            }}
            value={values.pics.length > 0 ? "Images Selected" : ""}
          />
        </>
      )}

      {values.category === "Bar" && (
        <>
          <InputField
            label="Add Tags *"
            placeholder="Add Tags"
            onChangeText={handleChange("tags")}
            onBlur={handleBlur("tags")}
            value={values.tags}
            error={errors.tags}
            touched={touched.tags}
          />
          <InputField
            label="Prices *"
            placeholder="Prices"
            onChangeText={handleChange("prices")}
            onBlur={handleBlur("prices")}
            value={values.prices}
            error={errors.prices}
            touched={touched.prices}
          />

          <MultipleImageSelector
            label="Pics *"
            onImageSelected={(images) => {
              console.log("Selected images:", images);
              setFieldValue("pics", images);
            }}
            value={values.pics.length > 0 ? "Images Selected" : ""}
          />
          <InputField
            label="Operational Hours *"
            placeholder="Eg: 09:00 AM - 09:00 PM"
            onChangeText={handleChange("hours")}
            onBlur={handleBlur("hours")}
            value={values.hours}
            error={errors.hours}
            touched={touched.hours}
          />
        </>
      )}

      {values.category === "Tourist Attraction" && (
        <>
          <InputField
            label="Add Tags *"
            placeholder="Add Tags"
            onChangeText={handleChange("tags")}
            onBlur={handleBlur("tags")}
            value={values.tags}
            error={errors.tags}
            touched={touched.tags}
          />
          <InputField
            label="Prices *"
            placeholder="Prices"
            onChangeText={handleChange("prices")}
            onBlur={handleBlur("prices")}
            value={values.prices}
            error={errors.prices}
            touched={touched.prices}
          />

          <MultipleImageSelector
            label="Pics *"
            onImageSelected={(images) => {
              console.log("Selected images:", images);
              setFieldValue("pics", images);
            }}
            value={values.pics.length > 0 ? "Images Selected" : ""}
          />
          <InputField
            label="Operational Hours *"
            placeholder="Eg: 09:00 AM - 09:00 PM"
            onChangeText={handleChange("hours")}
            onBlur={handleBlur("hours")}
            value={values.hours}
            error={errors.hours}
            touched={touched.hours}
          />
        </>
      )}

      {values.category === "Others" && (
        <>
          <InputField
            label="Add Tags *"
            placeholder="Add Tags"
            onChangeText={handleChange("tags")}
            onBlur={handleBlur("tags")}
            value={values.tags}
            error={errors.tags}
            touched={touched.tags}
          />
          <InputField
            label="Prices *"
            placeholder="Prices"
            onChangeText={handleChange("prices")}
            onBlur={handleBlur("prices")}
            value={values.prices}
            error={errors.prices}
            touched={touched.prices}
          />

          <MultipleImageSelector
            label="Pics *"
            onImageSelected={(images) => {
              console.log("Selected images:", images);
              setFieldValue("pics", images);
            }}
            value={values.pics.length > 0 ? "Images Selected" : ""}
          />
          <InputField
            label="Operational Hours *"
            placeholder="Eg: 09:00 AM - 09:00 PM"
            onChangeText={handleChange("hours")}
            onBlur={handleBlur("hours")}
            value={values.hours}
            error={errors.hours}
            touched={touched.hours}
          />
        </>
      )}
    </>
  );
};

export default CategoryFormFields;

`

While this works for rendering fields for two categories, I want to ensure the approach is scalable and maintainable, especially if I need to add more categories in the future. Additionally, I’m not sure about the best way to handle form validation with conditionally rendered fields.

Expected Outcome

I would like to know:

The best practices for dynamically rendering form fields based on category selection in React Native.
How to efficiently manage validation for conditionally rendered fields using Formik or any other recommended library.
Any example code or resources that demonstrate a similar implementation.
no action when submitting form.

Can you assign an elements class list to a variable by clicking on the element?

The main question I have is: Is there a way to assign to a variable an elements class list by clicking on said element.

Expanding on this, I’m trying to create a function that – on clicking an image in a photo grid – expands the image making it clearer for people to see. I made a for loop that loops through an array that contains the class lists of all images in the grid, the idea was that upon clicking on any one of the images a function that contains the loop would be called and the class list for the image that was clicked would be stored as a variable, the loop would then compare each value in the array to the variable and upon a match would apply a class that enlarges that particular image, this way I could use one function for every image in the grid instead of writing 15+ functions where each one was called depending on the image clicked. I’ve run into an issue when trying to retrieve the class list for the image that was clicked on – that being I can’t figure out how to retrieve the class list for an element by clicking on said element.

As I said I could just make 15+ different functions each with a variable directly assigning that specific images class but that hardly seems like the best way to do this. If this just isn’t possible also let me know please.

My JS as it stands:

function enlarge() {
    let figureArray = [] = document.querySelectorAll(".photo-grid figure");
    let figure = ; //This is where the class list of the clicked element would be stored
    for (let i = 0; i < figureArray.length; i++ ) {
        if (figureArray[i] === figure) {
            figureArray.item(i).classList.toggle("zoom"); 
        }
    }
};

unable to integrate custom indicators/studies using highcharts

i’m working on a forex broker an trying to integrate custom indicator using highcharts library in NEXTJS 14 but unable to come across a documentation for such
i initially used trading view but seem like to integrate an indicator one will need to go for a paid package which is high so how can i handle same with highcharts if not what other library could i try out for like stock/forex market data
below is the code

import HighchartsReact from 'highcharts-react-official'
import Highcharts from "highcharts/highstock";
import HighchartsExporting from 'highcharts/modules/exporting'
import patternFill from "highcharts/modules/pattern-fill";


    
    const fetchHighchartData = async () => {
            setchartData({
                data: [],
                data_volume: [],
                show_data: false
            })
            const data = await fetch(
                'https://demo-live-data.highcharts.com/aapl-ohlcv.json'
            ).then(response => response.json());
            // split the data set into ohlc and volume
            const ohlc = [],
                volume = [],
                dataLength = data.length;
    
            for (let i = 0; i < dataLength; i += 1) {
                ohlc.push([
                    data[i][0], // the date
                    data[i][1], // open
                    data[i][2], // high
                    data[i][3], // low
                    data[i][4] // close
                ]);
    
                volume.push([
                    data[i][0], // the date
                    data[i][5] // the volume
                ]);
            }
            setchartData({
                data: ohlc,
                data_volume: volume,
                show_data: true
            })
    
            console.log(this)
        }
    
    
    
        useLayoutEffect(() => {
            
            fetchHighchartData()
           
    
        }, [])
    
        const options = {
            chart:{
                width:'1000',
                height:'600'
            },
               
            title: {
                text: 'My chart',
                
            },
    
            yAxis: [{
                height: '75%',
                width:'100%',
                labels: {
                  align: 'right',
                  x: -3
                },
                title: {
                  text: 'AAPL'
                }
              }, {
                top: '75%',
                height: '25%',
                labels: {
                  align: 'right',
                  x: -3
                },
                offset: 0,
                title: {
                  text: 'MACD'
                }
              }],
            
    
            series: [{
                type:'candlestick',
                id: 'aapl',
                name: 'AAPL',
                data: chartData.data,
                
            },
            {
                type:'line',
                id: 'volume',
                name: 'Volume',
                data: chartData.data_volume,
                yAxis: 1
            }
            ]
        }
        console.log(options)
        
    
    
    
    
        return (
            <>
                {authData.logged_in ?
                    <Hero>
                        <main className={'bg-[#0B1215] lg:w-[100`enter code here`%] lg:h-[120vh]  max-xl:h-[100vh] lg:overflow-x-hidden md:h-[150vh] md:w-[100%] max-md:h-[100vh] max-md:w-[100%] '}>
    
                            <div className={'flex lg:w-full lg:h-[100%] md:h-full lg:flex-row p-2'}>
                                <aside className={' lg:flex lg:w-[25%] lg:h-[full] md:h-full p-5 md:hidden sm:hidden max-sm:hidden'}>
                                    <Rates handleGraphChange={handleGraphChange} />
                                </aside>
    
                                <div className={'flex lg:flex-row p-0 lg:w-[100%] lg:h-full md:w-[100%] md:h-[100%] sm:w-[100%] sm:h-[100%] max-sm:w-[100%] max-sm:h-[100%]  border-white bg-[#101720] max-md:flex-col max-xl:flex-col md:flex-col'}>
                                    <div className='flex flex-col w-[100%] h-[100%] p-2'>
    
                                        <div className='p-0 m-0 w-[100%] lg:h-[10%] flex justify-center items-center'>
                                            <FlipClockCountdown
    
                                                // to={new Date(expiry).getTime() + 24 * 3600 * 1000 + 5000}
                                                to={'2024-09-12'}
                                                className='h-full' title='Count-Down'
                                                labels={['DAYS', 'HOURS', 'MINUTES', 'SECONDS']}
    
                                                digitBlockStyle={{ height: 45, width: 25, backgroundColor: 'white', color: 'bg-[#0B1215]' }}
                                                // dividerStyle={{ color: 'white', height: 1 }}
                                                //  separatorStyle={{ color: 'red', size: '6px' }}
                                                labelStyle={{ fontSize: 15, fontWeight: 500, textTransform: 'uppercase', color: 'white', marginTop: '10%' }}
                                            />;
    
                                        </div>
    
    
                                        {/* 
                                        <div className='w-[100%] lg:h-[20%] md:h-[40%] sm:h-[50%] max-sm:h-[70%] p-2 grid lg:grid-cols-3 md:grid-cols-2 sm:grid-cols-2 max-sm:grid-cols-2  place-items-center' >
                                            <Filter />
                                        </div> */}
                                        <div   className='p-0 flex overflow-y-hidden justify-center items-center lg:w-[100%] lg:h-[90%] max-lg:w-[100%] max-lg:h-[70%] md:w-[100%] md:h-[70%] max-md:h-[100%] sm:w-[100%] sm:h-[100%] max-sm:w-[100%] max-sm:h-[100%]  '>
                                            {chartData.show_data ?
                                            
                                                <HighchartsReact
                                                    highcharts={ Highcharts }
                                                    options={options}
                                                    constructorType={'stockChart'}
                                                    className="[w-100%] h-[100%]"
                                                    
                                                />
                                                
                                                :
                                                <span className="loading loading-bars text-white loading-lg"></span>
    
                                                
                                            }
    
    
                                        </div>
                                    </div>
    
    
    
    
                                </div>
    
                            </div>
    
                        </main>
                    </Hero>
    
                    :
                    router.push('/')
    
                }
    
    
    
            </>
        )