Is it possible to store files in browser’s temporary folder and retrieve them using JavaScript?

I’m using a PDF viewer on the frontend which can only read .pdf URLs (it’s not able to read blob directly). So I’ll need to download those files to the user’s computer first. Hypothetically, this is what I want to do:

// download blob
let pdf = fetch(mysite.com);

// store in a temporary folder
// maybe "%AppData%LocalGoogleChromeUser DataDefaultCache"?
browser.storeFile(pdf);

// retrieve the file from temporary folder and pass to PDF viewer
myPDFViewer.load('%AppData%LocalGoogleChromeUser DataDefaultCachemy-file.pdf')

The PDF viewer I’m using can load offline files perfectly fine, as long as I have the absolute path to the file (ending with .pdf). I have tried all sorts of things but still not able to generate such .pdf URLs from the fetched blob.

So, is it possible to download files, store them in a temporary folder internal to the browser (which will get cleaned up automatically), and generate absolute local paths to those files?

Sharing Formik form field values between sibling React components

In a React app, I’m trying to sync data between two components – the primary component is a form (handled via the Formik library) and the second is a “preview”. As the user types data into the form, that data should appear in the “preview” component. The preview shows them what the data will look like in a special format our app uses.

It seems like a Context is the right way to sync data between two sibling components. I’m very new to React so I may be on the wrong track, if so please correct me.

Formik has a hook that allows me to get a field’s value as it changes:

const [field] = useField('firstName');

// would update each time the value changed:
// field.value = "b"
// field.value = "bo"
// field.value = "bob"

I have created a context:

const ServerContext = React.createContext();
const ContextProvider = ({ children }) => {
    const [preview, setPreview] = useState(0);

    return (
        <ServerContext.Provider value={{ preview, setPreview }}>
            {children}
        </ServerContext.Provider>
    );
};

My JSX has this context as a parent:

<ContextProvider>
  <Preview ...>
  <Formik ...>
</ContextProvider>

Based on examples, I can see how I would get the data/setter in my form component:

const { preview, setPreview } = useContext(ServerContext);

Yet, I can’t find an appropriate way to call setPreview.

This throws an error Cannot update a component ('ContextProvider') while rendering a different component:

const [field] = useField('serverName');
const { setPreview } = useContext(ServerContext);

setPreview({
    firstName: field.value
});

How can I do this?

Error Unable to find JSON file in folder, Javascript

Trying to fetch my json file, but apparently the URL is invalid or wrong as per the warning.
Tried to console log modelURL and it looks correct. Console.log Output : ./tm-my-image-model/model.json

Full error

Uncaught Error: Request to ./tm-my-image-model/model.json failed 

with status code 404
const URL = ./tm-my-image-model/;

let model, webcam, maxPredictions, happy, sad, angry;
let refresh = true;


    async function init() {
        if (refresh) {
            refresh = false;
            const metadataURL = URL + "metadata.json";
            const modelURL = URL + "model.json";
            
      console.log(modelURL)
}}

File Structure

enter image description here

How to access a variable from another typescript file

Say, I have the following typescript which contains enlightenFilters$ :

import { Component, Input, OnInit } from "@angular/core";
import { ConfigType, LisaConfig } from "app/enrichment/models/lisa/configuration.model";
import { Observable } from "rxjs";
import { EnrichmentFilters } from "../../models/lisa/filter.model";
import { select, Store } from "@ngrx/store";
import { EnrichmentFiltersState } from "../../reducers/enrichment-filters.reducer";
import { getPropertyEnrichmentFilters, getRateEnrichmentFilters } from "../../selectors/enrichment-filters.selectors";

@Component({
  selector: "app-lisa-config",
  templateUrl: "./lisa-config.component.html"
})

export class LisaConfigComponent implements OnInit {
  @Input() public config: LisaConfig;
  public enlightenFilters$: Observable<EnrichmentFilters>;

  constructor(private store$: Store<EnrichmentFiltersState>) {
  }

  ngOnInit() {
    switch (this.config.configType) {
      case ConfigType.RATE:
        this.enlightenFilters$ = this.store$.pipe(select(getRateEnrichmentFilters));
        break;
      case ConfigType.PROPERTY:
        this.enlightenFilters$ = this.store$.pipe(select(getPropertyEnrichmentFilters));
        break;
    }
  }
}

enter image description here

I want to access the above enlightenFilters$ from the following typescript and store it’s data into a variable named enlighten:

import { Component, Input } from "@angular/core";
import { Filter } from "app/enrichment/models/lisa/filter.model";
import { isArray, has } from "lodash";
import { LisaConfigComponent } from "app/enrichment/components/lisa-config/lisa-config.component";

@Component({
  templateUrl: "./filters.component.html",
  selector: "app-lisa-config-filters",
})
export class FiltersComponent {
  @Input() public filters: Filter[];
  // want to store data from enlightenFilters$ into enlighten
  // public enlighten: LisaConfigComponent;

  constructor() {}

  useGroupsLogic(filter: Filter): boolean {
    return isArray(filter.groups);
  }

  useKeywordsLogic(group: any): boolean {
    return has(group, "keywords");
  }
}

enter image description here

So that I can use enlighten into .html file like below:

<ng-container *ngFor="let filter of filters">
  <div>{{ filter.name }}
    <li *ngIf='{
        enlightenFilters: enlighten | async
      } as data'>
      <ng-container>
        <ul>
          <ng-container *ngFor="let enlightenFilter of data.enlightenFilters">
            <li *ngif="enlightenFilter.hasOwnProperty('description') && enlightenFilter.name === filter.name">
              <mat-icon
                #tooltip="matTooltip"
                style="cursor: pointer"
                matTooltip="Test Tooltip"
                matTooltipPosition="right"
              >info_outline</mat-icon>
            </li>
          </ng-container>
        </ul>
      </ng-container>
    </li>
  </div>
  <ul>
    <li *ngIf="filter.group">Group: {{ filter.group }}</li>
  </ul>
</ng-container>

enter image description here

How can I achieve this?

(I tried exporting from one typescript and importing in other one following https://bobbyhadz.com/blog/typescript-import-variable-from-another-file, it was not successful)

React: create closure that’s referntially equal across renders with useCallback

I need to create an event handler in React in a custom hook and I’d like the event handling function to be referentially equal across renders for ..reasons (yes I do see how I can do this w/o but I want to understand). Can I use useCallback as below to ensure the eventListener is referentially equal on every render by simply not mentioning variables it closes over in the dependencies (as below) or will that cause issues even if it’s never passed to a child component so I don’t need it to change value to trigger rerenders?

If not how can I achieve this? Does it matter if I can assume delay and fn don’t change (except perhaps it’s reference)?

export const useVisibleInterval = (fn, delay = 300000) => {
    const interval_id = useRef(null)
    const handleVisibilityChange = useCallback(() => {
        if (document.hidden || interval_id.current) return
        interval_id.current = setInterval(fn, delay)
        fn()
    }, [])
    const clearInt = () => {
        if (!interval_id.current) return
        clearInterval(interval_id.current)
        interval_id.current = null
    }
    const interval_run = () => {
        if (document.hidden) {
            document.addEventListener("visibilitychange", handleVisibilityChange)
            clearInt()
        } else fn()
    }
    const teardown = () => {
        document.removeEventListener("visibilitychange", handleVisibilityChange)
        clearInt()
    }
    useEffect(() => {
        interval_id.current = setInterval(interval_run, delay)
        return teardown
    }, [])
}

At a really high level, I’d like to understand what the dependencies for useCallback do. Are they just to force reference inequality so child components that depend on it rerender? Or does React memoize the result of function execution so failing to include dependencies would give stale results?

Best way to handle recursion with async functions and promises?

The following is pseudocode to illustrate my problem. The parent function must ultimately return a promise when all of the tasks are done (I’ve omitted the others for clarity). The parent function calls child functions and some of the child functions have to perform their tasks recursively and so, for clarity, I’ve separated them into worker functions. If there is a cleaner way I would love to learn it.

How best to handle the recursion in this example?

// This function must ultimately return a Promise.
async function parentFunction(uId) {
    try {
        await childFunction(uId);
        return Promise.resolve(uId);
    } catch (error) {
        console.log(error);
    }
}

async function childFunction(uId) {
    try {
        const done = await workerFunction(uId);

        if (done) {
            return Promise.resolve(true);
        } else {
            // There are more files to delete; best way to handle recursion?
        }
    } catch (error) {
        console.log(error);
    }
}

async function workerFunction(uId) {
    try {
        // Query the database, limit to 100 files.
        const query = await db.queryFiles().limit(100);

        if (query.size == 0) {
            // Nothing to delete, we're done!
            return Promise.resolve(true);
        }

        // Perform an atomic (all-or-none) batch delete that can only take 100 files at most.
        await db.batchDelete(query);
        
        // Batch delete successfull!
        if (query.size < 100) {
            // The query was less than 100 files so there can be no more files to delete.
            return Promise.resolve(true);
        } else {
            // There may possibly be more files to delete.
            // Return a promise or handle recursion here?
            return Promise.resolve(false);
        }
    } catch (error) {
        console.log(error);
    }
}

how do you pass a React hook useState() ‘s callback function to a web component’s attribute using Lit HTML

I am building a custom Web component to use with React, I am using React useState hook and
I need to pass it into my custom Web Component. I know that web component attributes only take strings and if I were to stringify my function it would lose its scope. So here in lies my problem. I am Using Lit HTML and React.

    function MyReactcomp() {
       const [state, setState] = useState("");
       return (
            <div className="Wrapper">
               <customweb-component updateState={setState} />
            </div>
        );
    }

How to create/order an Array based on data from other Array?

I’m developing the backEnd part for a selling app in which I have 3 Array of Objects, one got the sellers’ name, the second one has the monthly sales, and the other has the products being sold. Based on this information I was told by my superiors to generate an Array => with the product’s name, sorted from a to z, *with the condition that the product has exceeded 5000 units sold, and that it has been sold for a particular salesman.
These are the 3 Arrays:

const sellers = [
    {id:1,name: 'juan', age: 23},
    {id:2,name: 'adrian', age: 32},
    {id:3,name: 'apolo', age: 45}
  ];
const products = [
    { id: 1, credencial: "132254524", name: "televisores" },
    { id: 2, credencial: "143618668", name: "estufas" },
    { id: 3, credencial: "78903228", name: "celulares" },
    { id: 4, credencial: "176812737", name: "Audio" },
    { id: 5, credencial: "216352696", name: "heladeras" },
  ];

const sales = [
  { productsId: 2, sellerId: 1, quantity: 1200 },
  { productsId: 1, sellerId: 1, quantity: 500 },
  { productsId: 5, sellerId: 2, quantity: 20000 },
  { productsId: 2, sellerId: 3, quantity: 8401 },
  { productsId: 3, sellerId: 1, quantity: 2877 },
  { productsId: 3, sellerId: 2, quantity: 1736 },
  { productsId: 2, sellerId: 3, quantity: 2965 },
  { productsId: 4, sellerId: 4, quantity: 1651 },
  { productsId: 5, sellerId: 1, quantity: 700 },
  { productsId: 1, sellerId: 1, quantity: 7956 },
];

This is what I have tried:

const namesArray = sales.filter(e => e.productsId=== 3 & e.sellerId===3)
    const array= []
    namesArray.forEach(element => {
   const test= namesArray.filter(e => e.sellerId===element.id)

Don’t take that lines of code too seriously, not proud of them, just wanted to show what I tried.
However, the end result should look like this:

const result= ['celulares', 'estufas' ]

Is it possible to custom the distance between 2 labels (on x-axis)

Is it possible to custom the distance between 2 labels (on x-axis) in chart.js?

In chart.js, the distance between two labels will be constant over time, but I want to be make the distance between the first label and y-axis smaller than the distances between other two labels.

Curve I have now:

enter image description here

Effect I want to get (not talking about the difference between graphs, but talking about the distances between labels on axis)

enter image description here

Any help will be appreicated!

useEffect won’t update state

I’m creating a simple tomato app and got stuck on the timer update logic.

I’m using a useEffect to update a timer, but for some reason after the one second, the timer stop decreasing. It seems it’s not getting updated since the console log keep printing the initial values .

here’s a testable stackbliz

here’s the full component:

import './Tomato.css';
import { useState, useEffect } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faPlay, faPause, faArrowsRotate, faArrowDown, faArrowUp } from '@fortawesome/free-solid-svg-icons'

function Tomato() {
    
    const [settings, setSettings] = useState({session: 25, break: 5});
    const [timer, setTimer] = useState({minutes: '25', seconds: '00', active: false, isBreak: false});
    

    useEffect(() => {
        let timerInterval;

        if(timer.active) {
            timerInterval = setInterval(() => {
                let seconds = parseInt(timer.seconds);
                let minutes = parseInt(timer.minutes);
                console.log(seconds, ':',minutes)
                if(seconds === 0 && minutes === 0) {
                //  setTimer( {
                //      minutes: settings.isBreak ? settings.session : settings.break, 
                //      seconds: '00', 
                //      active: true, 
                //      isBreak: !settings.isBreak
                //  })
                //  // TODO BIP
                } else if(seconds === 0) {
                    const newTimer = {
                        ...timer,
                        minutes: timer.minutes-1,
                        seconds: '59',
                    }
                    setTimer( newTimer)
                } else {
                    console.log('in')
                    seconds = seconds - 1;
                    // this is not working as expected
                    setTimer( {
                        ...timer,
                        seconds: seconds < 10 ? '0'+seconds : seconds+''
                    })
                }
            }, 1000);
        } else {
            clearInterval(timerInterval);
        }

        return function cleanup() {
            clearInterval(timerInterval);
        };
    }, [timer.active]);


    const toggleTimer = (value) => {
        setTimer({ ...timer, active: value})
    }

    const refreshTimer = () => {
        setTimer({ 
            minutes: settings.session,
            seconds: '00', 
            active: false,
            isBreak: false
        })
    }

    const editSettings =  (type, val) => {
        if(timer.active) return
        const newSettings = { ...settings }
        newSettings[type] +=val;
        if(newSettings[type] > 60) {
            newSettings[type] = 60
        }
        if(newSettings[type] < 1) {
            newSettings[type] = 1
        }
        setSettings(newSettings)
    }

    return (
        <div className="Tomato">
            
            <h2 className="title">Session</h2>
            <div className="session-container">
                <div className='session-value'>{timer.minutes}:{timer.seconds}</div>
                <div className='controls-container'>
                    <span className='icon-container'>
                        <FontAwesomeIcon onClick={()=>{ toggleTimer(true)}} icon={faPlay} />
                    </span>
                    <span className='icon-container'>
                        <FontAwesomeIcon onClick={()=>{ toggleTimer(false)}} icon={faPause} />
                    </span>
                    <span className='icon-container'>
                        <FontAwesomeIcon onClick={()=>{ refreshTimer()}} icon={faArrowsRotate} />
                    </span>
                </div>
            </div>

            <h2 className="title">Session Length</h2>
            <div className="setting-container">
                <span className='icon-container' onClick={()=> editSettings('session', -1)}>
                    <FontAwesomeIcon icon={faArrowDown} />
                </span>
                <div className="setting-value">{settings.session}</div>
                <span className='icon-container' onClick={()=> editSettings('session', 1)}>
                    <FontAwesomeIcon icon={faArrowUp} />
                </span>
            </div>
            
            <h2 className="title">Break Length</h2>
            <div className="setting-container">
                <span className='icon-container' onClick={()=> editSettings('break', -1)}>
                    <FontAwesomeIcon icon={faArrowDown} />
                </span>
                <div className="setting-value">{settings.break}</div>
                <span className='icon-container' onClick={()=> editSettings('break', +1)}>
                    <FontAwesomeIcon icon={faArrowUp} />
                </span>
            </div>
            
        </div>
        );
    }
    
    export default Tomato;
    

Copy element text

So, I am trying to copy to clipboard a string of text from an HTML container. When I output the string into console it looks fine, but when i paste what I copied it outputs the var name.

$("body").on("click", ".emName", function() {        
    var ctnm = $(this).text(),
        temp = $("<input>");
    
    console.log(ctnm);

    $("body").append(temp);
    temp.val(ctnm).select();
    document.execCommand("copy");
    temp.remove();       
});

What am I missing here?

Write a program to print the odd numbers from a given range in javascript

Input:
Input consists of multiple lines. Each line has two numbers, separated by a space, which indicate a range.

Output:
Print all the odd numbers (ascending order) within the range (inclusive), separate them by a space and separate each output set by a line break.
If there is no odd number within the range, print “none” (without quotes).
Code evaluation is based on output, please do NOT print anything else.

enter image description here

Custom Event on JavaScript Class

How can i create an event that is attached to a class object.
I have to create a class that has an event that should be called at a certain time.
the class looks like this and should call the event “newMember” when a new one is added.
what works is that i attach a custom event to the window and call it which is not my goal.

Not NodeJS

class Room {
    constructor() {
        this.members = {}
    }
    addMember(data) {
        if (!this.members[data.remotesid]) {
            this.members[data.socket] = data.identity
            //this.dispatchEvent();
        } else {
            console.log('Member already in room')
        }
    }
}

Redux best practice to filter data

in the process of developing an application, I’m facing a question about whether I’m using Redux correctly.
I have a fav:[] in which I add product objects and render their list. However, in order for the data not to be lost, I have to copy this fav:[] to favCopy:[] and only after that execute .filter
Example code:

case "fav":
                state.fav = action.payload.filter === 'all'
                    ? state.favCopy
                    : state.favCopy.filter((item: any) => item[type] === action.payload.filter)

                break;

I would like to understand how right I am by keeping the original array intact? Maybe there is a way not to multiply arrays and use only one state?