I need a help to execute javascript dynamic function function (pageContext) { return (pagecontext[“n2”] * pagecontext[“n3”] ) } in flutter

          public func evaluateJS(functionName : String, argument : [String: Any?]) -> Any? {
    let jsFunc = self.replaceSubContextWithActualValue(key: functionName)
    let jsFunctionVal = "func = " + jsFunc
    let context = JSContext()
    _ =  context?.evaluateScript(jsFunctionVal)
    let jsFunction = context?.objectForKeyedSubscript("func")
    let result = jsFunction?.call(withArguments:[argument])
    return result?.toObject()
}

the above code executes like above in ios

Not executing setInterval every time

I am making a stopwatch.
I want to display the interval between the time the start button is pressed and now in a p tag at any moment.
I tried this:

watch() {
      const p = document.createElement("p");
      p.id = "p";
      document.body.appendChild(p);
      document.getElementById("p")!.innerHTML = this.stop();
   }
   start() {
      if(this.status === 'started') throw new Error('already started');
      this.currentTime = Date.now();
      this.interVal = setInterval(() => this.watch(), 100);
      this.status = 'started';
      return this.interVal;
   }
   stop() {
      if(this.status === 'stopped') throw new Error('already stopped');
      this.duration = Date.now() - this.currentTime + this.duration;
      console.log(this.duration);
      this.status = 'stopped';
      return this.duration;
   }

How to add a check icon with MUI or Tailwind CSS to all the selected value in the dropdown list?

I want to add a small check/tick icon beside the value eg: Operations ✓ if user selects operations in the TopicList dropdownlist. The TopicList is a class component to get the data from the database which consist of:
Operations, Array, Repetition, Function, Selection. If user selects 2 different values then eg:
Operations ✓
Array ✓
Repetition
Function
Selection.
How can I modify this code to solve this issue?
Here is an image of how I would like it to be if user selects Array.
enter image description here

import axios from "axios";
import React, { useState } from "react";
import TopicList from "../Components/topicList";
import CheckIcon from '@mui/icons-material/Check';

function CreateEvent(success, message) {
  const navigate = useNavigate();
  const [selectedValues, setSelectedValues] = useState([]); // array to store selected values

  const getDataFromTopicList = (val) => {
    if (val !== "" && !selectedValues.includes(val)) {
      setSelectedValues([...selectedValues, val]);
    }
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log(selectedValues); // selectedValues array contains all selected values from all TopicList components

    axios({
      method: "POST",
      url: BASE_URL + "events/submitEvent",
      data: {
        topicId: selectedValues,
      },

      headers: { "Content-Type": "application/json" },
    })
      .then((response) => {
        if (response.status === 200) {
          toast.success("Successfully Created", {
            position: toast.POSITION.TOP_CENTER,
          });
        } else {
          toast.error(response.data.message, {
            position: toast.POSITION.TOP_CENTER,
          });
        }
      })
      .catch((err) => {
        if (err.response) {
          toast.error(err.response.data.message, {
            position: toast.POSITION.TOP_CENTER,
          });
        } else {
          toast.error("Failed to Create", {
            position: toast.POSITION.TOP_CENTER,
          });
        }
      });
  };

  return (
    <div className="">
      <div>
        <form
          onSubmit={handleSubmit}
        >
          <h1>
            Create an Event
          </h1>
          <div>
            <div>
              <TopicList
                selectedValues={selectedValues}
                getDataFromTopicList={getDataFromTopicList}
              />
            </div>
          </div>
        </form>
      </div>
    </div>
  );
}

export default CreateEvent;
import axios from "axios";
import React from "react";
import CheckIcon from "@mui/icons-material/Check";

const BASE_URL = process.env.REACT_APP_BASE_URL;

export default class TopicList extends React.Component {
  state = {
    topics: [],
  };

  componentDidMount() {
    axios.get(BASE_URL + `events/topic`).then((res) => {
      const topics = res.data;
      this.setState({ topics });
    });
  }

  render() {
    return (
      <select required onChange={(val) => this.getCat(val.target.value)}>
        {this.state.topics.map((topic) => (
          <option value={topic.topicId}>
          {topic.topic}
          {this.props.selectedValues.includes(topic.topicId) && <CheckIcon style={{ color: "green" }} />}
        </option>
        ))}
      </select>
    );
  }
}

How to return back data through GET from flask route to jquery and load it in dependent dropdown

@app.route('/loadsubcat', methods =['GET'])
def loadsubcat():
sub_cat = request.args.get('category_id')
sub_cat_data = subcategories.query.filter(subcategories.categoryID == sub_cat).all()
sub_data = "example"
return jsonify({"hello": sub_cat_data})

<script type="text/javascript">
$("#parent_cat").change(function() {
var cat_id = $(this).val();
$.ajax({
type: 'GET',
url: "/loadsubcat",
data: { category_id: cat_id },
contentType: 'application/json',
dataType: 'json',
success: function(sub_cat_data){
alert(sub_cat_data);
for (var i = 0; i < data.length; ++i) {
console.log(data[i].subcategory_name);
}
$("#sub_cat").empty();
var output = "";
$.each(JSON.parse(data), function(a,b){
// console.log(data);
output += "<option value='"+b.id+"'>"+b.subcategory_name+"  </option>"
$("#sub_cat").append(output);
});
}
});
});
</script>

I am trying to send first dropdown value to route then fetch results and based on that first dropdown value i am passing i am trying to load my second dependent dropdown.

I am stuck how to send data back through get api which is fetched through database.

How to replace word in a paragraph using Javascript

I am new to JS and would like to add words to a sentence or replace words, specfically like this:

HTML file:

<body>
<p id="paragraph"> 
My name is <first> <last>. I have been at ... for <years> and plan to <goals> after completing my courses. <p>

  <script src="script.js">
    var paragraph = document.getElementById("paragraph");
    paragraph.replace("first", "firstName");
    paragraph.replace("last", "lastName");
    paragraph.replace("years", "yearsOfStudy ");
    paragraph.replace("goals", "goal");
    
  </script>
<body> 

JS file:

let firstName = "Max";
let lastName = "Jones";
let yearsOfStudy = "about a year";
let goal = "getting a job as a software developer";

This isnt working as intended but I dont know why. Please help me figure this out, it doesnt matter if its using the replace method or another method as long as the varibales declared in the JS file are being used and an inline script is used to insert those words into the text.

How to add class after onclick Reactjs

I am working on Reactjs,I have list of questions(using loop) with radio button
and i want to add class on radio button which clicked,But right now unable to add class,
Here is my current code

<FormControlLabel
                    key={`radio${item.id}${count + 2}`}
                    value={item.id.toString()}
                    control={<Radio color="primary" required={item.required} />}
                    label={getChoice(item)}
                    onClick={myfunct}
                  />
                ))}

And in juqery i am using following code

   const myfunct = event => {
         $(this).addClass('my-selected-item');
     }

Listen for value changes in an object property, slice and subscribe to the changed value

I use the Async local-storage with angular to store data in the indexedDB.
The library has a method to listen to / watch for changes.

This method returns an Observable with the complete object.

What I want is to slice the changed property value, object, or the array of the object and subscribe to it.

My example object would be:

{
    fetched: boolean,
    loaded: boolean,
    item: null, // object
    list: [],   // object arry
}

Now I need to watch for the changes in each property as an Observable.

fetched$.subscribe((fetched: boolean)) => {}
loaded$.subscribe((loaded: boolean)) => {}
item$.subscribe((item: any)) => {}
list$.subscribe((list: any[])) => {}

Here is the code I used to slice the changed value so far.

// slice an individual value
function sliceValue<T, U>(
  repo: BaseRepository<T, U>,
  key: string
): Observable<any> {
  if (!repo.key || !repo.store.has(repo.key)) {
     return of (null);
  }

  return repo.store.watch(repo.key).pipe(
    distinctUntilChanged((prev, curr) => {
      if (!prev || !curr) return false;
      return prev[KEY.D][key] === curr[KEY.D][key];
    }),
    switchMap((ctx: any) => repo.store.get(repo.key)),
    map((ctx: any) => ctx[KEY.D][key]));
}

// State class
export class TestState extends BaseRepository<TestModel> {

  public fetched$: Observable<boolean> = sliceValue(this, 'fetched');
  public loaded$: Observable<boolean> = sliceValue(this, 'loaded');
  public item$: Observable<boolean> = sliceObject(this, 'item');
  public list$: Observable<string> = sliceList(this, 'list');

  constructor(
    public readonly store: StorageMap,
  ) {
    super(store);
  }
  
}

But I do not know the efficient way to do it.

If there is any other best way to do it, I would like to know and try it out.

Thank you very much.

Failed prop type: MUI: The getting warning in reactjs + mui?

I am getting below warning when I try to open datepicker on click on icon. I am getting this error.

I am doing like this

const DatePickerTextField = React.forwardRef((props: TextFieldProps, ref) => {
  const theme = useTheme();
  return <TextField {...props} size="small" InputLabelProps={{}} />;
});
export const DDatePickerTextField = styled(DatePickerTextField)<TextFieldProps>(
  ({ theme }) => {
    return {};
  }
);

export default DDatePicker;

I am using like this

<DDatePicker
          {...restDate}
          value={value}
          onChange={callAll((newValue: Date) => {
            onChangeI(newValue);
          }, onChangeRef.current)}
          renderInput={
            !!renderInput
              ? renderInput
              : (params) => {
                  return (
                    <DDatePickerTextField
                      {...params}
                      {...textFieldProps}
                      ref={params.inputRef}
                      inputRef={ref}
                      name={name}
                      error={!!error}
                      helperText={error?.message}
                    />
                  );
                }
          }
        />

how to fix this issue ?

Warning: Failed prop type: MUI: The `anchorEl` prop provided to the component is invalid.

enter image description here

“Uncaught TypeError: Store.getBooks is not a function (app.js:81)”

I found it odd that I came across the function mentioned because I did include it but it seems like that my application is not picking up on it. I set the function as a Store constructor :

function Store() {}

and then added a prototype that will refer to the function like this :

Store.prototype.addBook = function(book) {
    const books = Store.getBooks(); <-- where the issue is happening

    books.push(book);

    localStorage.setItem('books', JSON.stringify(books));
}

the outcome I expected was that I will add books that I add in my application as an array but it throws an error instead.

Select all checkbox is not selecting second page but its selecting a first page its how possible?

I am using table . In that i am using in table head a checkbox for select all . I using pagination also . when i click select all checkbox. it selecting a single page . balance pages is not selecting.

All Employees

The Above code is used in table head .
The bellow code is used in table body.

My function is

function change() {

    var checkboxes = document.getElementsByName('PerticularEmployees[]');
    
    $('#PerticularEmployees:checkbox').each(function () {
        this.checked = true;
    });

console.log(checkboxes );

}

In that the problem is this line var checkboxes = document.getElementsByName(‘PerticularEmployees[]’); shows only the checkbox are listed in page one not showing all the pages.

I am trying if i gave a select all in table head checkbox . it may select automatically all the checkbox including all the page. Please help to complete this task

installed local npm package is not symlinked

I have installed a local npm package via:

npm i ./my_modules/mypackage

It shows up in my dependencies as:

  "dependencies": {
    "mypackage": "file:my_modules/mypackage"
  }

when I look at the node_modules folder, it shows up in there as well, but it is not symlinked

there is no arrow icon in the explorer indicating it is symlinked

which means I have to rebuild every single time I want to see changes inside the local package

this only just started happening today, I’m not sure why it’s not symlinking all of the sudden

how do I resolve this issue so that it symlinks properly? it used to do this automatically and now it isn’t. I’ve even tried re-installing everything on my dev machine and it is still doing this behaviour.

normally when I install a local npm package it will symlink it properly, automatically

now, for whatever reason, it is not symlinking

EDIT

I’ve even tried using npm link

cd my_modules/mypackage
npm link
cd ../../
npm link mypackage
npm I ./my_modules/mypackage

still doesn’t symlink.

Overlapped slide still getting clicked

The slide that I turned the opacity to 0 on is still clickable even though I set pointer events to none. Basically I have 2 slides on this slideshow and even if i’m on the first slide when I click on it, it goes to the 2nd slides hyperlink.

        //programming slideshow

        $(function () {
            var slide_index = 1;
            displaySlides(slide_index);
            function nextSlide() {
                displaySlides(slide_index++);
            }
            function prevslide() {
                displaySlides(slide_index--);
            }
            function displaySlides() {
                var i;
                var slides = document.getElementsByClassName("programming-slides");
                if (slide_index > slides.length) { slide_index = 1 }
                if (slide_index < 1) { slide_index = slides.length }
                for (i = 0; i < slides.length; i++) {
                    slides[i].style.opacity = 0;
                }
                slides[slide_index - 1].style.opacity = 1;
                for (var i = 0; i < slides.length; i++) {
                    // If the slide is not visible, set its pointer-events to none
                    if (slides[i].style.opacity === '0') {
                        slides[i].style.pointerEvents = 'none';
                    } else {
                        // Otherwise, set its pointer-events to auto
                        slides[i].style.pointerEvents = 'auto';
                    }
                }
            }
            var next = document.getElementById('programming-next');
            next.addEventListener('click', nextSlide);

            var prev = document.getElementById('programming-prev');
            prev.addEventListener('click', prevslide);
        })

Should Passwords and Username be visable in request tab of network tab?

I’m working on a login system (the current code refers to changing the password as an example but is relative);

An example of the code using axios for changing a password;

(please do not comment on the current localStorage code, I am aware of its flaws. this is testing purposes and this question strictly relates to the password)

axios.put(
        'http://localhost:5001/auth/changePassword',
        {
            currentPassword: password.currentPassword,
            newPassword: password.newPassword,
        },
        {
            headers: { accessToken: localStorage.getItem('accessToken') },
        }
    )
    .then((response) => {
        if (response.data.error) {
            alert(response.data.error)
        } else {
            alert(response.data.message)
        }
    })

If i click the request tab I can see the password in plaintext, this is kind of jarring , is there no way somebody unauthorised could see this in a similar fashion?. I have hashing on the server side no problem and auth tokens etc etc. But being able to see the password so plain like this ….. is this actually a problem ?

Screenshot of password samples

Function components cannot be given refs.attempts to access this ref will fail

I am getting below waring .I am trying to use react hook form with material UI.

I know problem is here ref={params.inputRef} but don’t know how to show this problem.

here is my code
https://codesandbox.io/s/relaxed-bas-79e66x?file=/src/hook-date-picker.tsx:2849-3569

<DDatePicker
          {...restDate}
          value={value}
          onChange={callAll((newValue: Date) => {
            onChangeI(newValue);
          }, onChangeRef.current)}
          renderInput={
            !!renderInput
              ? renderInput
              : (params) => {
                  return (
                    <DDatePickerTextField
                      {...params}
                      {...textFieldProps}
                      ref={params.inputRef}
                      inputRef={ref}
                      name={name}
                      error={!!error}
                      helperText={error?.message}
                    />
                  );
                }
          }
        />

here is my text field

const DatePickerTextField = (props: TextFieldProps) => {
  const theme = useTheme();
  return <TextField {...props} size="small" InputLabelProps={{}} />;
};
export const DDatePickerTextField = styled(DatePickerTextField)<TextFieldProps>(
  ({ theme }) => {
    return {};
  }
);

any idea and suggestion ?

**[![Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?][1]][1]**