REACT- Where to start if I code the backend? [closed]

I have developped all my frontend based on the use of 2 json files. Now, I want to submit a form, push&fetch data, save data from input fields when refreshing a tab. I have a potential architecture for my datatabse. How do I start for the api (React Query seems good if you have any proposol for the api) and the backend? I don’t know where to start. For now, I just want to developp everything on localhost (not using dockers)…

Here the code

How to access static images in Nuxt production application hosted on Vercel?

I’ve got a website hosted on Vercel where I’m trying to use an image in the static folder as a favicon.

The static folder is in the root directory of the repository. Inside my nuxt.config.js file, I’m referencing the image like below:

module.exports = {
  mode: 'universal',
  router: {
    base: '/'
  },
  head: {
    link: [
      {
        rel: 'icon',
        type: 'image/x-icon',
        href: `/images/meta/favicon.ico`
      }, 
    ],
  }
}

This works locally, but doesn’t work with my production site which is hosted with Vercel.

I tried changing the href of the favicon to an image that is already online which worked, confirming that the issue seems to be with the local images in my app.

The Vercel output file structure from the build process looks as follows:

enter image description here

For some reason, all files outside of the ‘_nuxt’ folder aren’t able to be accessed – this is also the case for the files in the js folder and fonts folder (e.g. when I try to access https://hownow-git-dev-hownow.vercel.app/js/adhoc.js I’m getting a ‘script not found’ error).

Am I missing some sort of configuration setting to allow me to access these files?

Getting day in javascript cause an error (NaN)

I am using luxon library in my application.
I don’t understand why i get here an error:

console.log(luxon.DateTime.fromISO('2022-11-31').day) //  NaN ?
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.3.2/luxon.js"></script>

In the case above i get NaN but i expect 31. But in the next case: DateTime.fromISO('2022-11-30').day i get 30. Why in the first case i get NaN and how to get the expected value?

this.setState ({id: event.currentTarget.id}) не сохраняет id при повторном вызове [closed]

Прошу помочь!

Когда я нажимаю на кнопку добавить в корзину, я беру id товара и передаю в корзину без проблем, но когда я нажимаю на другой товар, то id со state заменяется на новый id и получается, что в корзину не добавляется новый товар, а просто заменяется старый на новый =(

Я понимая, что currentTarget берет id, но при повторном вызове заменяет на новый id. Вопрос: как сохранить прошлые id в state?

clickCartId = (event) => {this.setState ({id: event.currentTarget.id} )}

Angular Interceptor – EmptyError: no elements in sequence Error

I have the following HTTP interceptor:

import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpRequest,
  HttpHandler,
  HttpInterceptor,
} from '@angular/common/http';
import { Observable, EMPTY } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router';

@Injectable()
export class UnauthorizedInterceptor implements HttpInterceptor {
  constructor(private router: Router) {}
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      catchError((err: any, caught) => {
        if (err.status === 401) {
          this.router.navigate(['/authenticate/login']);
        }

        return EMPTY;
      })
    );
  }
}

And I want to navigate to the login page if the response is 401.
The redirect is happening and the web page navigates to authenticate/login, but in the console, the following error is thrown:

 EmptyError: no elements in sequence

If I replace return EMPTY with return caught then the request will be called indefinitely.

What I’m I doing wrong?

ReactJS: How do you call an async fuction on button click?

How can I call fetchData() on button a click ?
Should i call the fucntion using useEffect ?

function Subscriptions() {
  const [allUsers] = useState([]);
  useEffect(() => {
    fetchData = async () => {
      try {
       // some code
      } catch (err) {
        console.log(err);
      }
    };
  }, []);
  return (

<Button onclick={fetchData()}>Fetch Data</Button>

);
}
export default Subscriptions;

                                                                                                                   

PHP Laravel/Livewire Get data from controller to script JS in the HTML view

In a PHP Laravel project, I have a function showCurve($1, $2) (launched by a click in the page), which put data in a variable of the controller.

@foreach ($CurveLimI2T as $curve => $val)
<li><span class="caret" wire:click="showCurve('{{$val['id']}}', '{{3}}')">{{$val['name']}}`</span>

The controller line of work :

$this->dataListPointsMin = $tabFinal_Min;

With dd(), I can see the data in the variable at this point.

So in the view, I get this variable to make work and load the data to a chart via a script at the end of the page.
But the variable was empty and nothing appear ..

<script><?php $dataMin = json_encode($this->dataListPointsMin, JSON_NUMERIC_CHECK);?>

I use the same method an another page and the data are in the $this->myvariable and i can get it and work.

The chart was on the same page than the click function showCurve().

Did I have forget anyhting ?

Improve RegEx to match gTLD, Umlaut-Domains etc

I’d like to validate an input using JavaScript. The input should allow domains (including subdomains) but not any protocol or port. It also should allow an Umlaut like ÄäÖöÜü:

Example (allowed):

Example (not allowed):

This is what I got so far:

/^(?!://)([a-zA-ZäöüÄÖÜß0-9]+.)?[a-zA-ZäöüÄÖÜß0-9][a-zA-ZäöüÄÖÜß0-9-]+.[a-zA-Z]{2,6}?$/i

This works, but I am limited to all the characters I separately added (äöü…) and it does not look very elegant.

How can I improve the expression?

Having trouble using Barba.js and seperate JS files

I’ve setup Barba.js on my WordPress website. It seems to be working. the only thing is that when I transition to other pages, my other JS files don’t load until a hard refresh.

I think to solve this, I have to use namespace and BeforeEnter and re-run my seperate JS file within that

The only problem is I don’t know how to do that. I’ve looked all over the net.

I’ve tried this (which I know is not right, but maybe on the right track?)

let script = document.createElement('script');
script.src="/flickity.init.js";   
next.container.appendChild(script);

Any help would be appreciated 🙂

Thanks in advance!

Optimal function javascript to eliminate duplicates

So let’s say i have a variable that stores a big string and where the
is the separator to the next word. whats the best way to eliminate duplicate words using the
as the indicator.

So imagine we have this:

var notRemoved= ” I am col 1
I am col 2
I am col 11
I am col 1
I am col 2

And the result should be like this:

var removed= ” I am col 1
I am col 2
I am col 11 “

Customize browser’s built-in right-click context menu using JavaScript?

Is there any API (even if non-standard and only for a particular browser) to customize the options shown in the browser’s context menu when the user right-clicks on a web page?

I’m aware of the possibility to catch the contextmenu event and then render a custom “context menu” using HTML and CSS, but was wondering if there’s a way to use and customize the system’s built-in context menu widget.

Unable to parse nested array from agg

I am trying to find a nice solution, how to parse values from nested array placed at 3rd level in JSON at path aggregations.platform.buckets:

{
    "aggregations": {
        "platform": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 82264,
            "buckets": [{
                "key": 8021,
                "doc_count": 29504028,
                "instance_count": {
                    "count": 29504028,
                    "min": 1.0,
                    "max": 262082.0,
                    "avg": 80.40741138803149,
                    "sum": 2.372342517E9
                }
            }, {
                "key": 23131,
                "doc_count": 4049023,
                "instance_count": {
                    "count": 4049023,
                    "min": 1.0,
                    "max": 55660.0,
                    "avg": 3.1212976562494212,
                    "sum": 1.2638206E7
                }
            }, {
                "key": 5021,
                "doc_count": 2356190,
                "instance_count": {
                    "count": 2356190,
                    "min": 1.0,
                    "max": 48840.0,
                    "avg": 52.9123521447761,
                    "sum": 1.24671555E8
                }
            }
....

I have this code:

$.ajax({
        url: esurl,
        type:'post',
        data: jsonQuery,
        crossDomain: true,
            async: false,
        dataType: "text",
        contentType: "application/json; charset=utf-8",
        success: function(response) {
                //var obj       = JSON.parse(response.aggregations.platform.buckets);
                var obj         = JSON.stringify(response);
                contentType: "application/json; charset=utf-8",
                console.log("Response: " + response);
                console.log("Response Obj: " + obj);
                
                $.each(response.aggregations.platform.buckets , function(key , value){ // First Level
         $.each(value.key , function(k , v ){  // The contents inside stars
             console.log(v)
         });     
    });

            }
    } );

I have found some inspirations here in other chats but no one is working.

When trying to parse it using JSON.parse with full path I will get error:
Cannot read properties of undefined (reading 'platform') at line var obj = JSON.parse(response.aggregations.platform.buckets);

If I use the above code I am getting same error at line $.each(response.aggregations.platform.buckets , function(key , value).

Any idea how to parse i.e. the path response.aggregations.platform.buckets.key?

React-Native Flatlist all Flatlist Rerender on one Item Selection

I’m building a React-Native app and trying to optimize it i runned into the case of my Flatlist.

So this Flatlist basically renders few elements and each of these elements are selectable.
The issue i’m facing is that selecting one single item rerenders the whole Flatlist, and thus all items it contains.

I’ve seen a lot of solutions online already, and tried them without any success.

Here is my code :

Class component containing the Flatlist


const keyExtractor = (item) => item.id

export default class OrderedList extends Component {

    state = {
        selected: null,
    }

     onPressSelect = (id) => {
         console.log(this.state.selected)
         if(this.state.selected === id) {
             this.setState({ selected: null})
         } 
         else {
             this.setState({ selected: id})
         }
     }


    renderItemOrdered = ({item}) => {

        const { group, wording, description, id: uniqueID } = item
        const { id, name } = group

        return (
            <CategoryCard
            type="ordered"
            // item={item}
            uniqueID={uniqueID}
            groupName={name} 
            groupID={id} 
            description={description} 
            title={wording}
            selected={this.state.selected}
            onPressSelect={() => this.onPressSelect(item.id)}
            />
        )
    }

    render() {
    return (
        <FlatList 
        initialNumToRender={10}
        maxToRenderPerBatch={10}
        data={this.props.data}
        renderItem={this.renderItemOrdered}
        keyExtractor={keyExtractor}
        extraData={this.state.selected} --> Tried with and without it
        />
      )
    }

}

Class component containing the renderItem method

export default class CategoryCard extends Component {

    shouldComponentUpdate = (nextProps, nextState) => {
      return nextProps.selected !== this.props.selected &&
        nextProps.onPressSelect !== this.props.onPressSelect
    }


render(){
    if(this.props.type === 'ordered') {
      return (
        <Pressable style={this.props.selected === this.props.uniqueID ? styles.cardContainerSelected : styles.cardContainer} onPressIn={this.props.onPressSelect}>

          <View style={[styles.cardHeader, backgroundTitleColor(this.props.groupID)]}>
              <Text style={[styles.cardGroupName, textTitleColor(this.props.groupID)]}>{this.props.groupName}</Text>
          </View>


          <View style={styles.cardContent}>
              <Text style={styles.cardTitle}>{this.props.wording}</Text>
              <Text style={styles.cardDescription} numberOfLines={3} ellipsizeMode="tail">{this.props.description}</Text>
          </View>

        </Pressable>
      )
    }
}

}

What i already tried :

At first my components were functional components so i changed them into class components in order to make things works. Before that, i tried to use React.memo, also to manually add a function areEqual to it, to tell it when it should rerender, depending on props.
It didn’t give me what i wanted.
I also tried to put all anonymous functions outside return statements, made use of useCallback, played around the ShouldComponentUpdate (like adding and removing all the props, the onPress prop, selected props)… None of that worked.

I must be missing something somewhere.. If you can help me with it, it would be a big help !