FlatList conditional rendering if {user === owner || gues}

In my Applikation I render a Expo FlatList to show created Events.

List Preview

If the user has created or joined this event, he should be able to see the images. If not, they should be hidden.

I would now store the creator and the guests in the database and would have to compare this with the currentUser from the Firebase Auth beforehand.

However, I face the problem that I can’t tell the FlatList which items should be rendered and which shouldn’t.

Does anyone knows a solution for conditional render a FlatList?

Fullcode

import React, { Component } from 'react';
import { FlatList, Box,  } from "native-base";
import { StyleSheet } from 'react-native'
import EventCard from "./EventCard.js";
import { collection, getDocs } from 'firebase/firestore';
import { firestore, auth } from '../firebase.js'
import { getStorage } from "firebase/storage"

export default class Events extends Component {

    constructor(props) {
        super(props);
        this.currentUser = auth.currentUser
        this.navigation = this.props.navigation
        this.storage = getStorage()
        this.querySnapshot = getDocs(collection(firestore, 'events'));
        this.state = {
            isLoading: true,
            fetch: false,
            eventData: {
                adress: '',
                hosts: '',
                description: '',
                eventtitle: '',
                invitecode: '',
                key: '',
                timestamp: '',
                owner: '',
            }
        }
    }

    componentDidMount() {
        this.loadEventsFromFirebase()

    }

    //  reload on pull down
    onRefresh() {
        this.setState({
            fetch: true
        });
        this.loadEventsFromFirebase()
    }

    loadEventsFromFirebase() {
        let data = []
        this.querySnapshot.then(querySnapshot => {
            querySnapshot.docs.map(doc => {
                data.push(doc.data())
            })
            this.setState({
                eventData: data,
                fetch: false,
            });
        });

    }

    render() {

        return (
            <Box style={styles.container} _dark={{ bg: "blueGray.900" }} _light={{ bg: "blueGray.50" }}>
                <FlatList
                    showsVerticalScrollIndicator={false}
                    onRefresh={() => this.onRefresh()}
                    refreshing={this.state.fetch}
                    data={this.state.eventData}
                    keyExtractor={item => item.key}
                    renderItem={({ item }) => (<EventCard key={Date.now()} eventData={item} />
                    )}
                />
            </Box>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        alignSelf: 'stretch',
        alignItems: 'center'
    },
})

Calculating max and avg values from two arrays

I am trying to use two arrays to calculate max value and average values to create key/value object.
Here are the two arrays

const products = ["car", "car", "motorcycle", "motorcycle"] // key
const prices =[2000, 1500, 800, 900] // value

desire outcome - 
{"car" : {max: 2000, average: 1750}, 
"motorcycle":{max: 900, average: 850} }

It will be great if ES6 iterators like reduce/map and etc can be used for solution.

Thank you for help!

Is there anything like i want to add my navbar on every website using my own chrome extension? [closed]

I’m building one chrome extension with Reactjs and it’s work is to show stock details on top of every website and it’s position should be fixed, but I’m facing one issue that is my extension navbar is overlapping website navbar.

I want to add my custom navbar then website own page.

I have used document.body.appendChild() also added position: fixed
But not working.

Recent grad revisiting a 2021 plain JS app project. Issues running front end server with Webpack [closed]

I graduated a couple weeks ago with a Certificate in Full Stack Development. Post graduation, we’re instructed to revisit and revise older projects. One of which, I accidentally deleted package.json files as well as all node.js files. Don’t ask me how. Ashamed to say if a recruiter asked me to demonstrate booting up a vanilla JS server app, I’d be in trouble. If he/she asked me about file source control with Github, I’d be in deep trouble as well. Most commits have disappeared. Unfortunately, these topics were briefly mentioned within the course curriculum and now I’m having to go back and research. I suppose Ive been so accustomed to react and rails setup that I forgot how to start up a plain server without either frameworks. With each Youtube tutorial and package.json configuration, I grow more confused as to how to get things back up and running. To be more specific, it seems my updated webpack configurations do not permit me to render code to the browser from localhost8080. The console error says GET http://localhost:8080/ 404 (Not Found) I do not know where to begin to resolve this issue. Still lost after hours of tutorial videos. Any help is gladly appreciated.
Git Repository: https://github.com/jasonronalddavis/ManyProjectsFrontend
Terminal error log:

ERROR in ./src/style.css (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].use[1]!./src/style.css)
Module build failed (from ./node_modules/css-loader/dist/cjs.js):
ValidationError: Invalid options object. CSS Loader has been initialized using an options object that does not match the API schema.
 - options has an unknown property 'minimize'. These properties are valid:
   object { url?, import?, modules?, sourceMap?, importLoaders?, esModule?, exportType? }
    at validate (/Users/jasondavis/Flatiron/code/ManyProjectsFrontEnd/node_modules/schema-utils/dist/validate.js:105:11)
    at Object.getOptions (/Users/jasondavis/Flatiron/code/ManyProjectsFrontEnd/node_modules/webpack/lib/NormalModule.js:585:19)
    at Object.loader (/Users/jasondavis/Flatiron/code/ManyProjectsFrontEnd/node_modules/css-loader/dist/index.js:31:27)
 @ ./src/style.css 8:6-127 22:17-24 26:7-21 58:25-39 59:36-47 59:50-64 63:6-73:7 64:54-65 64:68-82 70:42-53 70:56-70 72:21-28 83:0-97 83:0-97 84:22-29 84:33-47 84:50-64 61:4-74:5

webpack 5.70.0 compiled with 1 error in 17776 ms

chart.js scale xaxis with date, strange renderer

Hi i got this renderer with my config on chart.js, i dont understand why i got

enter image description here

this is the version of chart.js

/*!
 * Chart.js
 * http://chartjs.org/
 * Version: 2.7.1
 *
 * Copyright 2017 Nick Downie
 * Released under the MIT license
 * https://github.com/chartjs/Chart.js/blob/master/LICENSE.md
 */

i generate my chart with this function and i dont understand how to fix my problem
thanks for your help

new Chart(document.getElementById("line-chart"), {
        type: 'line',
        data: {
            labels: datadate,
            datasets: [{ 
                data: datavalue,
                label: "Value array",
                borderColor: "#3e95cd",
                pointRadius: 3,
                pointHoverRadius: 3,
                fill: false
                }
            ]
        },
        options: {
                title: {
                display: true,
                text: 'returned value'
                },
                
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: false
                        }
                    }],
                    xAxes: [ {
                        type: 'time',
                       time: {
                        min: Math.min.apply(null, datadate),
                        max: Math.max.apply(null, datadate)
                       }
                    }],
                },
                responsive: true
        }
    });

How to encode a remote image into base64 string?

I have an image url

url = "https://images.unsplash.com/photo-1511884642898-4c92249e20b6?ixlib=rb- 
1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80"

Can anyone tell me please how can I encode this remote image into base64 string in javascript…

Why do my filters work separately from each other?

I have two selections that are supposed to filter data, they work but separately, how do I make them filter data together?

When I click on the second select, it resets the data from the first one. They filter the same data array, so the result is new all the time, I don’t understand how to filter an already filtered array

How do I make a joint filter?

 //filter data
  const [allData, setAllData] = useState<ICompanie[]>(companiesData);

  // status filter
  const handleStatusFilter = (status: string): void => {
    const filterData = companiesData.filter((item) => {
      if (item.status === status) {
        return item;
      }
    });

    setAllData(filterData);
  };

  // category filter
  const handleCategoriesFilter = (category: string): void => {
    const filterData = companiesData.filter((item) => {
      if (item.category === category) {
        return item;
      }
    });

    setAllData(filterData);
  };

Angular Modal Error-cannot read properties of undefined (reading ‘classList’) –

I am trying to call modal from my cardetails page
normla modals didnt fit for me and i used angular ngb bootstrap modal
Modal opens when i click open button

BUT
it gives error no the console.
error at console: picture

Actually there are two modals at different pages and they have different component ts code but they give same error.
IT is not related with html code .

this is cardetails.html where is modal .open button is located(at the bottom)

<div class="card" style="width:100%;margin-top: 20px;">

  <div class="row"style="max-height: 80%;">

  </div>
    <carousel  style="height:95%; width: 100%;" >
      <slide *ngFor="let imagePath of carImagePaths; let index=index" >
        <img [src]="imageUrl+imagePath" alt="image slide"class="image-fluid" style=" height:400px;width: 100%; object-fit: cover">
    
        <div class="carousel-caption">
          <h4>Görsel: {{index+1}} </h4>
          <p></p>
        </div>
      </slide>
    </carousel>
  


      <!-- car detail sayfası araç detay bilgileiri -->
      <div *ngFor="let car of cars" class="card-body">
        <div class="card-body detailsFontInfo">

            <h5 class="card-title">
            {{ car?.brandName }} || {{ car?.modelName }}
            </h5>
            
        </div>
    
        <ul class="list-group list-group-flush  detailsFontInfo">
            <li class="list-group-item"><b>Renk :</b> {{ car?.colorName }}</li>
            
            <li class="list-group-item  detailsFontInfo"> <b>Model Yılı :</b> {{ car?.modelYear }}</li>

            <li class="list-group-item  detailsFontInfo"> <b>Günlük Fiyat :</b> {{ car?.dailyPrice | currency: "USD":true:"1.2-2" }}</li>

            <li class="list-group-item  detailsFontInfo"><b>Açıklama:</b> {{ car?.description }}</li>
            <li class="list-group-item  detailsFontInfo"><b>Kira Durumu :</b> {{ car?.isRentable ? "Uygun Değil" : "Müsait" }}</li>


           
            <!-- <b>Status : </b> {{ carDetail?.isRentable ? "Available" : "Not Available" }} -->
            
        </ul>
    </div>
    <!-- alt butonlar -->
    <div style="margin-bottom: 4%;">
      <div class="row">
        <div class="btn-goback col-md-2 offset-md-8">
          <button style="width: 100%;" routerLink="/cars" type="button" class="btn btn-outline-dark">
            Geri Dön
          </button>
        </div>


          <!-- giriş yapılmamışsa giriş yap -->
        <div class="col-md-2"*ngIf="!isAuthenticated()">
            


            <!-- burada modal çıksın ve desin ki kiralayabilmek için kayıt olun veya giriş yapın -->
            <button (click)="openLoginModal()" style="width: 100%;" type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#carDetailIsAuthModal">
              Kirala
            </button>
        </div>


        <!-- giriş yapılmamışsa rentala git -->

        <div class="col-md-2" *ngIf="isAuthenticated()">
          <!-- eğer giriş yapılı ise kirala butonuna bassın RENT MODAL GELSİN  -->

          <button (click)="openRentalModal()" style="width: 100%;" type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#carDetailsRentalModal">
            Kirala
            
          </button>
          
       </div>

      </div>
    

      
</div>

this is cardetails.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { CarDetails } from 'src/app/models/carDetails';
import { CarImage } from 'src/app/models/carImage';
import { CarImageService } from 'src/app/services/car-image.service';
import { CarService } from 'src/app/services/car.service';
import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { NonNullAssert } from '@angular/compiler';
import { LoginComponent } from '../login/login.component';
import { RentalComponent } from '../rental/rental.component';
import { RentalService } from 'src/app/services/rental.service';

@Component({
  selector: 'app-cardetail',
  templateUrl: './cardetail.component.html',
  styleUrls: ['./cardetail.component.css']
})
export class CardetailComponent implements OnInit {
  //carDetail:CarDetails[]= [];
  cars: CarDetails[] = [];
  carImagePaths:string[] = [];
  carDetail: CarDetails;
  dataLoaded = false;
  imageUrl:string="https://localhost:44396/Uploads/images/"
  //--for rental
  
 
  
  
  carImages:CarImage[]=[];//slider için

  constructor(private carImageService: CarImageService,
    private carService: CarService,
    private activatedRoute: ActivatedRoute,
    public modalService:NgbModal,
    private rentalService:RentalService,
    ) { }

  ngOnInit(): void {


    this.activatedRoute.params.subscribe(params => {//car id verilirse ki arabaya tiklayinca verilmis olur: icerdeki emthodlari calistir

      if(params['carId']){
          this.getCarsDetailsByCarId(params['carId'])
         // this.getImagesByCarId(params['carId'])

        }
    })

    
  }

 
  




  getCarsDetailsByCarId(carId: number){//details sayfamızdaki araç detaylarını çekiyor
    this.carService.getCarsDetailsByCarId(carId).subscribe((response)=>{
      this.cars=response.data
      this.carDetail = response.data[0];//sıfırıncı eement bilgilerin olduğu kısım,sonra mesaj felan geliyor
      
      this.carImagePaths=this.carDetail.imagePath
      this.dataLoaded = true;

    })
  }

  // geçici olarak login li isAuthenticated:true/false mutlaka sil bunu sonra
  isAuthenticated(){
    return false
  }
    
  openLoginModal() {//LOGİN MODAL ı açar (cardetailhtmldeki buton)
    let modalRef=this.modalService.open(LoginComponent)
  }
  openRentalModal(){
    let modalRef= this.modalService.open(RentalComponent)
    //buraya tıkalyınca hem rentala gitmeli
    
  

  }
  
  

  
}

MODALS HTML İS EMTY OR FULL DOESNT MATTER SAME ERROR

MODALS TS

import { Component, OnInit } from '@angular/core';
import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor(public modal:NgbActiveModal) { }

  ngOnInit(): void {
  }

}

Any ideas might help

What does the […] mean in JavaScript? [duplicate]

I’m currently watching a video about getting unique values from an array object:

Javascript:

const menu = [
    {
        name: 'pancakes',
        category: 'breakfast',
    },
    {
        name: 'burger',
        category: 'lunch',
    },
    {
        name: 'steak',
        category: 'dinner',
    },
    {
        name: 'bacon',
        category: 'breakfast',
    },
    {
        name: 'eggs',
        category: 'breakfast',
    },
    {
        name: 'pasta',
        category: 'dinner',
    },
]

const categories = [...new Set(menu.map((item) => item.category))];

He wanted to get the unique category values (i.e. breakfast, lunch, dinner) and put them inside an array. So he first wanted to use map() to get every instance in the category, then use Set() to only get the unique value.

My question is: What does the […] symbol mean (and what is it called)? I could not find anything on the internet about this.

Thanks!

making automated generate closing when using backtick

hi im currently wanted to ask is there an extension which help auto generate closing when i coding inside the backtick cuz whenever i code like javascript and i put like document.writeln(<p>text</p>) the <p> when i make as an paragraph it doesn’t generate </p> which mean i have to type again manually the closing of </p> , is there an extension to make it happen like auto generate even inside of backtick ? search at google but didnt give me any of result instead they recommending extension for vscode starter which make me more confused. please anyone can Help Thank you.

_app.tsx to have getInitialProps and other custom props too, need proper Typscript type

My _app.tsx files what to be something on these lines

interface CmsAppProps extends AppProps {
  pageData: boolean
}

const CmsApp: NextPage<CmsAppProps> = ({ Component, pageProps, pageData }) => {
  // ...some component details
}

CmsApp.getInitialProps = async (context: NextPageContext) => {
   // some data process here
   return {
     pageData: true
   }
}

Problem here is, typescript is throwing error as: Type '(_ctx: NextPageContext) => Promise<{ pageData: true; }>' is not assignable to type '(context: NextPageContext) => AmcAppProps | Promise<AmcAppProps>'

Looks like it expense me to return data same as what is argument of component props. I cannot return Component and pageProps from getInitialProps.

If I replace type NextPage with React.FC then it obviously doesn’t contain getInitialProps props. Plus doesn’t has relation like what is being sent from getInitialProps also will be passed on to the component.

Is there a correct way to put everything right in typescript?

Can’t open link containing special characters

I have Django app which I test on my local PC and then when I add something new, I upload changes to my company virtual server. I have a problem with links to files. Below is the code for links to attached files (both my local and server have the same code):

<p class="article-content mt-2 mb-1"><strong>Attachment: </strong><a href="{{post.file_close.url}}">{{post.file_close.name}}</a></p>

If I upload file cars.png everything works fine in both versions. This works no matter the extension, pdf, excel, image, etc.
Problem is, if I upload file carsčč.png it fails only on server side, on my PC it works great.
I get the following error on my Django/debugg:

Page not found (404)
“C:inetpubfilesPyWebmediaPN_files202236cars” does not exist

Like the link is not complete, it stopped as soon as it runs into a special character.
But, shown link still containes all the letters, it’s PN_files/2022/03/06/carsčč.png
Tried:
I looked at regional settings, it’s the same on both PCs. Is there something else I could check or change? Maybe include something in the link?
Also, when I manually search for the file, the name is not currupted, it’s saved localy as carsčč.png. So I guess it’s only the link, tring to get the file.
I figured out it’s because of diacritic letters. On my ‘base.html’ I have meta charset="utf-8". Django setting LANGUAGE_CODE = 'hr-BA'.

I use Bootstrap 4.0 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">