i want to build e-commerce application with react and redux

i was devide the data and state of the application into slice,i used the sliceReducer in this project because it have so many component and have a lot of products categories to buy so when i try to make the first components which is about mechanics product this error always display “×
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app
    See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.”
    so this mecanicsSliceProducts:
import {createSlice} from '@reduxjs/toolkit';

const mecanicsProducts = [{name:"aprilia404", description: "Aprilia404 cylindres en V longitudinal de 65° 4 temps,refroidissement au liquide distribution bi-arbre à cames (DOHC) quatre soupapes par cylindre ", img: 'C:/Users/ADMIN/Desktop/Bike project/banner/aprilia404', number: 12 ,moteur:"4 cylindres", vitesseMax: "140km/h", reservoir: '55l', price: 3000, quantity: 0, id: 0}, 
{name: "Aprilia Dosudoro", description:"L’Aprilia Dorsoduro est la moto fun par excellence.Née d'une intuition brillante d’Aprilia, elle a été créée dans le seul but de donner autant de plaisir que possible  ", img: 'C:/Users/ADMIN/Desktop/Bike project/banner/apriliascooter', number: 8 ,moteur:"bicylindre", vitesseMax:"260km/h", reservoir: "12l" ,price: 12500, quantity: 0, id:1}, 
{name: 'Aprilia Sr 50', description:"Estampillée du numéro 3 et peinte aux couleurs de l’Aprilia Alitalia Racing Team, l’engin ne devrait pas passer inaperçu.", img: 'C:/Users/ADMIN/Desktop/Bike project/banner/aprilia sr 50', number: 12, moteur:"monocylindre", vitesseMax: '100km/h',reservoir: '7l', price: 4000, quantity: 0, id:2}, 
{name: "Ducati monter", description: "Ducati Monster est une gamme de motos du constructeur italien Ducati de type roadster lancée en 1992", img: 'C:/Users/ADMIN/Desktop/Bike project/banner/ducati monster 110s2009 modele3d', number: 12, moteur: "2 cylindres", vitesseMax: '260km/h', reservoir: "14l" ,price: 14500, quantity: 0, id: 3},
{name: "Honda cbr 600", description:"La Honda CBR600RR est une moto de 599 cm³, de la famille des CBR introduite par Honda en 2003", img: 'C:/Users/ADMIN/Desktop/Bike project/banner/honda 623 cbr bike', number: 5, vitesseMax: '260km/h', moteur: "4 cylindres, 4temps, refroidissement liquide", reservoir:"18.1l", price: 23400, quantity: 0, id:4}, 
{name: "Forza ftm", description: "Cyclomoteur FORZA-FTM ,Cylindrage 110CC , Charge utile : 110 Kg , Vitesse Max : 160 Km/h , Réservoir : 4.5Litres.", img: 'C:/Users/ADMIN/Desktop/Bike project/banner/forzaftm', number: 15, moteur: "monocylindre", vitesseMax: "160km/h", price: 2400, quantity: 0, id: 5}];

export const mecanicSliceProducts = createSlice({
    name: 'mecanicsProducts',
    initialState: mecanicsProducts,
    reducers: {
        changeQuantity: (state, action) => {
          let {name, newQuantity} = action.payload;
          let findProductName = state.find(product => product.name === name);
          if (findProductName) {
            findProductName.quantity = newQuantity;
          }
         return state;
        },
      buyProduct: (state, action) => {
        const purchasedProduct = state.find(product=> product.id === action.payload.id);
        if(purchasedProduct) {
            purchasedProduct.quantity += 1;
            purchasedProduct.number = purchasedProduct.number - purchasedProduct.quantity;             
        }
        return [...state, purchasedProduct]
      }
    

    }

});

export const selectPurchasedProducts = (state) => {
    return state.mecanicsProducts.filter(product => product.quantity !== 0).map(product => product.id)
};
    export const selectmecanicsProductsToDisplay = (state) => {
        return state.mecanicsProducts.map(product => ({
            name: product.name,
            img: product.img,
            price: product.price,
            id: product.id
        }))
    };
    console.log(selectmecanicsProductsToDisplay)

    export const {changeQuantity, buyProduct} = mecanicSliceProducts.actions;

export default mecanicSliceProducts.reducer;

this is the mecanicsProduct.js file:

import React from 'react';
import { selectmecanicsProductsToDisplay } from './mecanicSliceProducts';
import {useSelector} from 'react-redux';
import { Product } from '../Product.js'


export const MecanicProducts = () => {
    const mecanicsProducts = useSelector(selectmecanicsProductsToDisplay);
    console.log(mecanicsProducts);

return (
<div className="mecanics" >
<h2> Motors selections</h2>
{mecanicsProducts.map(product => <Product product={product} key={product.id} />
)}
</div>
    )
}

this is the store.js file :

import { configureStore } from '@reduxjs/toolkit';
import  mecanicSliceProductsReducer   from '../../features/mecanicsProducts/mecanicSliceProducts';

export const store = configureStore({
    reducer: {
        mecanicsProducts: mecanicSliceProductsReducer,
    }
})

this is the index.js file:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { App } from './App';
import { Provider } from 'react-redux';
import { store } from './components/App/store.js';


ReactDOM.render(
  
  <Provider store={store} >
    <App />
    </Provider >,
 
  document.getElementById('root')
);

this is the App.js file :

import React from 'react';
import { Navbar } from './components/Navbar/Navbar';
import {MecanicProducts} from './features/mecanicsProducts/mecanicsProducts'
 

export function App() {
  return (
    <div className="App">
      <Navbar />
      <MecanicProducts />
    </div>
  );
}

How do I parse the indentation level of a string into a JSON Object?

I’d like to be able to parse a string into a JSON Object, something like this (the text can be anything, I’m just putting them like this so you can see the structure):

A
  A-A
  A-B
    A-B-A
    A-B-B
  A-C
    A-C-A
B

into a json object, structured like this:

[
  {
    "root": "A",
    "content": [
      { "root": "A-A", "content": [] },
      {
        "root": "A-B",
        "content": [
          { "root": "A-B-A", "content": [] },
          { "root": "A-B-B", "content": [] }
        ]
      },
      {
        "root": "A-C",
        "content": [
          { "root": "A-C-A", "content": [] }
        ]
      }
    ]
  },
  { "root": "B", "content": [] }
]

So far, I have the following, but I’m not sure if this is the best way of doing it. Maybe a recursive approach would be better?

  let body = [];
  let indentStack = [0];
  for (let line of input.split('n')) { // input is the string I'd like to parse
    if (line.trim() == '') continue; // skips over empty lines
    let indent = line.match(/^ +/);
    indent = indent ? indent[0].length : 0; // matches the first group of spaces with regex, gets the indent level of this line
    if (indentStack[indentStack.length-1] != indent) 
      if (indentStack.includes(indent)) indentStack.length = indentStack.indexOf(indent)+1; // remove all indent levels after it as it's returned back to a higher level
      else stack.push(indent);
    console.log(`${(indent + '[' + indentStack.join() + ']').padEnd(10, ' ')}: ${line}`); // debugging
      
    if (indentStack.length == 1) body.push({ root: line, content: [] });
    else {
      body[body.length-1].content.push({ root: line.substring(indent), content: [] })
    }
  }
  console.log(body)

Dynamically changing the variable name inside 2 for loops [duplicate]

So I’m working in babylon.js (but is more a js problem at this time) my problem is that I need to change a variable name dynamically but taking the index of both for that.

Here, let me show you the array in fact:

    for (let i = 0; i < torresIndex; i++) {
                for (let j = 0; j < repTorre[i]; j++) {
                    piso = BABYLON.MeshBuilder.ExtrudePolygon("piso"+i+j, {shape:torre[i], depth: 1, sideOrientation: -1 }, scene);
                    piso.position.y = factorTamano++;
                    factorTamano = factorTamano++;
                    piso.material  = materialforSolidPolygon;
                    piso.enableEdgesRendering(); 
                    piso.edgesWidth = 4.0;
                    piso.edgesColor = new BABYLON.Color4(0, 0, 0);
  }
}

“piso” is an array variable outside of the loop.

So the idea in question is that the name of the variable “piso” change dynamically according to the position of “i” and “j”

The expected result is this:

i=0 j=1
piso01
i=0 j=2
piso02
......... and so on.

The end result in general that I want is that I can call the shape in question and take their vertices to work it out individually in another for loop.

How to checkbox automatically checked all when select all after upload image

I want to make a method that when executed will check all inputs that have images and text, where this method will run on the input checkbox with the label Select All, which when select all is checked automatically all the input checkboxes on the uploaded image will be checked. Like the example I made on the imageChecked() method which worked successfully where when the input is checked, the checked image data will be entered/returned to the image array in crudData{‘image’:[]}, and the text input data will be entered/returned to the array name in crudData{‘name’:[]}. Does anyone understand the case I’m asking about? Thank you.

Here is the complete code https://jsfiddle.net/cd59bLxu/1/

export default {
  data() {
    return{
      crudData:{
        ‘id’: null,
        ‘name’: [],
        ‘image’: [],
        ‘arrImage’: [],
      },
    }
  },
  methods: {
    imageUpload(e, maxItem){
      …
    },
    uploadImage(e){
      …
    },
    removeImage(key){
      …
    },
    imageChecked() {
      let checkedImages =          this.crudData.arrImage.filter(img =>   img.checked)
      this.crudData.image =   checkedImages.map(img => img.image)
      this.crudData.name = checkedImages.map(img => img.name)
      console.log({imageFiles:    this.crudData.image, names:       this.crudData.name})
    }
  }}

Reset count when another button is pressed

I have a lots of articles that have 1, 2, 3 or 4 pictures. On mobile I created a carousel. All images all on the same line and I have a count that is 0. And when I press on the right button(for example) that count it will be -100 and all images will have a left: -100 and so on. The problem is that, let’s say, I press on the button from one article that count will be -100. but after I go to another article and if I press again the count is not -100 and is -200. How can I reset that count when I change the article. The code is something like:

<div class="article">
  <div class="minus">Minu</div>
  <div class="plus">Plus
  </div><div class="num">0</div>
</div>
<div class="article">
  <div class="minus">Minu2</div>
  <div class="plus">Plus2
  </div><div class="num">0</div>
</div>
<div class="article">
  <div class="minus">Minu3</div>
  <div class="plus">Plus3
  </div><div class="num">0</div>
</div>
<div class="article">
  <div class="minus">Minu4</div>
  <div class="plus">Plus4
  </div><div class="num">0</div>
</div>
<div class="article">
  <div class="minus">Minu5</div>
  <div class="plus">Plus5
  </div><div class="num">0</div>
</div>
 var c = 0;
$('.plus').on('click', function(){
    c += 100
    $(this).siblings('.num').text(c)
})```

Google maps API: When going to the site with www and without, the Google maps doesn’t load consistently

When going to the site with www and without, the Google maps doesn’t load consistently.

I am using the google maps api on my site and getting the “This page didn’t load Google Maps correctly. See the JavaScript console for technical details.” error, but only in certain scenarios.

Going to https://www.[site].com/ the Google maps sections shows the error.
Going to https://[site].com/ the google maps pages does show with no error.

I am getting “Uncaught TypeError: can’t access property “prototype”, d is undefined” in the console (for the www only) … see attached image.

Because it does load sometimes I do not believe it is an issue with the key, but I could be wrong.

Console Error Image:

unsuccesful login with react

Let there be a landing page that enables the login.
This landing page has:

  • Text field for user ID: LoginUserIDInput
  • Text field for password: LoginPasswordInput
  • Button to start the login process: LoginButton

If the login process is successful, I am redirected to a private page.
If the login process is not successful, I remain on the landing page.

Now the following error message appears in the console output:

`controlId` is ignored on `<FormControl>` when `id` is specified.

How can I successfully implement the login process ?

AuthenticationAction.js

export const SHOW_LOGIN_DIALOG ='SHOW_LOGIN_DIALOG';
export const HIDE_LOGIN_DIALOG ='HIDE_LOGIN_DIALOG';

export const AUTHENTICATION_PENDING = 'AUTHENTICATION_PENDING'
export const AUTHENTICATION_SUCCESS = 'AUTHENTICATION_SUCCESS'
export const AUTHENTICATION_ERROR = 'AUTHENTICATION_ERROR'

export function getShowLoginDialogAction(){

    return {
        type: SHOW_LOGIN_DIALOG
    }
}

export function getHideLoginDialogAction(){

    return{
        type: HIDE_LOGIN_DIALOG
    }
}

export function getAuthenticateUserPendingAction(){
    return{
        type: AUTHENTICATION_PENDING
    }
}

export function getAuthenticationSuccessAction(userSession) {
    return {
        type: AUTHENTICATION_SUCCESS,
        user: userSession.user,
        accessToken: userSession.accessToken
    }
}

export function getAuthenticationErrorAction(error){
    return {
        type: AUTHENTICATION_ERROR,
        error: error
    }
}

export function authenticateUser(userID, password){

    console.log("Authenticate")
    return dispatch => {
        dispatch(getAuthenticateUserPendingAction());
        login(userID,password).then(userSession => { const action= getAuthenticationSuccessAction(userSession);
        dispatch(action);}, error => {dispatch(getAuthenticationErrorAction(error));}).catch(error=> {dispatch(getAuthenticationErrorAction(error));})
    }
}

function login(userID,password){
    const requestOptions={
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({userID, password})
    };
    return fetch('http://localhost:8080/login',requestOptions).then(handleResponse).then(userSession => {return userSession});
};

function handleResponse(response){

    const authorizationHeader = response.headers.get('Authorization');
    return response.text().then(text => {
        console.log('Receive result: '+authorizationHeader)

        const data= text && JSON.parse(text);
        var token 
        if(authorizationHeader){
            token = authorizationHeader.split(" ")[1];
        }
        if(!response.ok){
            if(response.status ===401){
                logout();
            }
            const error =(data && data.message) || response.statusText;
            return Promise.reject(error);
        }
        else{
            let userSession = {
                user: data,
                accessToken: token
            }
            return userSession;
        }
    });
}

function logout(){
    console.error("Should logout user")
}

RootReducer.js

import * as authenticationActions from '../actions/AuthenticationAction'

const initialState = {
    user: null,
    loginPending: false,
    showLoginDialog: false
    };
    function rootReducer(state = initialState, action) {
        console.log("Bin im Reducer" + action.type)

        switch(action.type){

            case authenticationActions.SHOW_LOGIN_DIALOG:
                return {
                    ...state,
                    showLoginDialog: true,
                    error: null
                }
         
        case authenticationActions.HIDE_LOGIN_DIALOG:
                return {
                    ...state,
                    showLoginDialog: false,
                    error: null
                }
        

        case authenticationActions.AUTHENTICATION_SUCCESS:
            {
                return {
                    ...state,
                    showLoginDialog: false,
                    pending: false,
                    user: action.user,
                    accessToken: action.accessToken
                }
            }
        case authenticationActions.AUTHENTICATION_ERROR:
            {
                return {
                    ...state,
                    pending: false,
                    error: "Authentication failed"
                }
            }
        case authenticationActions.AUTHENTICATION_PENDING:
            {
                return {
                    ...state,
                    pending: true,
                    error: null
                }
            }
            default:
                return state;
        }
        
    };
    
    export default rootReducer;
    

UserSessionWidget.js

import React, {Component} from "react"
import {connect} from "react-redux";
import { bindActionCreators } from 'redux'
import Button from "react-bootstrap/Button"
import Modal from "react-bootstrap/Modal"
import Form from "react-bootstrap/Form"
import * as authenticationActions from '../actions/AuthenticationAction'

const mapStateToProps = state => {
    return state;
}



class UserSessionWidget extends Component {

    constructor(props){
        super(props)
        this.state={username: '', password: ''};
        this.handleShow=this.handleShow.bind(this);
        this.handleClose=this.handleClose.bind(this);
        this.handleChange=this.handleChange.bind(this);
        this.handleSubmit=this.handleSubmit.bind(this);
    }

    handleShow(e){
        e.preventDefault();
        /* this.setState({show: true}) */
        const {showLoginDialogAction} =this.props;
        showLoginDialogAction();


    }
    handleClose(e){
        e.preventDefault();
        this.setState({show: false})
        const {hideLoginDialogAction} =this.props;
        hideLoginDialogAction();

    }

    handleChange(e){

        const {name,value} = e.target;
        this.setState({[name]: value})

        console.log(JSON.stringify(this.state))

    }

    handleSubmit(e){
        e.preventDefault();
        const {username, password} =this.state;
        const {authenticateUserAction}=this.props;
        authenticateUserAction(username, password);
        console.log("Pushed submit")
    }

    render(){

        var showDialog=this.props.showLoginDialog;
        if(showDialog==undefined){
            showDialog=false;
        }
     

        return (
            
            <div>
                <Button variant="primary" onClick={this.handleShow}>Login</Button>
                <Modal show={showDialog} onHide={this.handleClose}>
                    
                    <Modal.Body>
                    <Form>
  <Form.Group className="mb-3" controlId="userID">
    <Form.Label>UserID</Form.Label>
    <Form.Control id="LoginUserIDInput" type="text" placeholder="User ID" name="userID"
onChange={this.handleChange} />
   
  </Form.Group>

  <Form.Group className="mb-3" controlId="formBasicPassword">
    <Form.Label>Password</Form.Label>
    <Form.Control id=" LoginPasswordInput" type="password" placeholder="Password" name="password" onChange={this.handleChange} />
  </Form.Group>
 
  <Button variant="primary" type="submit" onClick={this.handleSubmit}>
    Submit
  </Button>
</Form>
                    </Modal.Body>
                    <Modal.Footer>
                        <Button variant="primary" onClick={this.handleClose}>Close</Button>
                    </Modal.Footer>
                   
                </Modal>
            </div>
        )
    }
}

const mapDisaptchToProps = dispatch => bindActionCreators({showLoginDialogAction: authenticationActions.getShowLoginDialogAction,hideLoginDialogAction: authenticationActions.getHideLoginDialogAction, authenticateUserAction: authenticationActions.authenticateUser},dispatch)
const ConnectedUserSessionsWidget =connect(mapStateToProps,mapDisaptchToProps)(UserSessionWidget)

export default ConnectedUserSessionsWidget;

jquery.js and jquery.keyframes.js are not found when using NPM

I’m having trouble using jquery and jquery.keyframes. I use NPM and the js files are stored in the node_modules folder while the html files are stored in the public folder. For some reason the html file cannot find the js files when I use this code:

<script src="../node_modules/jquerykeyframes/dist/jquery.keyframes.js"></script>
<script src="../node_modules/jquery/dist/jquery.js"></script>

I’ve tried a few alternatives but nothing has worked. What am I doing wrong?

How to to save txt file on server in HTML/JS?

I’m making signup form stuff and I want to save data to server and I got this code :

function Signup()
   {
     var text = "hello world",
   blob = new Blob([text], { type: 'text/plain' }),
   anchor = document.createElement('a');

anchor.download = "hello.txt";
anchor
anchor.href = (window.webkitURL || window.URL).createObjectURL(blob);
anchor.dataset.downloadurl = ['text/plain', anchor.download, anchor.href].join(':');
anchor.click();
   }

But its download file and I’m wondering how to save/download it to server.

How to fetch data from the mongo dB by given an array

I need some help. I am building an Api for recipes according to the ingredient, calorie and meal which I get from the user. so according to given ingredient I have to fetch recipes from the database which include required ingredient. I have two collection first collection of recipes which have document of recipes and these recipes document have a field ingredient from which I am searching ingredient. but here problem arise that I have a Calories and meal queries also. I can explain this with an example so let say I get queries from user like

localhost:5000/getcalorie/salmon,Fish,Turkey,Pork,ham?calorie=1400&meal=3 

so here salmon fish are ingredient. but here I have to divide calorie into 3 meals like 20% 40% and 40% and fetch those recipes which have calorie less than 20% calorie, 40% and 40%
and also no recipes should repeat in any meal like if roasted salmon is in breakfast then it should not be in lunch or dinner. but they have different recipes or salmon like salmon patties in lunch and for dinner it something other.
So how can I do this

I will show you how I am doing

async function meals(array,meals){
                let selectedfood =  await Recipe.find({$and:[{ingredients:{$in:array}},{calorie:{$lte:meals}}]})
                let selectedfood1 = await Nutrition.find({$and:[{name:{$in:array}},{calorie:{$lte:meals}}]})
                
                let commonselectedfoodarray = selectedfood.concat(selectedfood1)
                return commonselectedfoodarray
            }

from above code I am fetching recipes from database but here I am just including required ingredient from URL and meals(meals change according to meal like for breakfast it is (20/100)*calorie same for lunch and dinner)

but this above code fetch me recipes which have required ingredient and calories less than a meal

but my problem is how can I handle not repetition of recipes in different meals

Assert a script is present on the page using nightwatchjs

I’m using nightwatchjs and trying to test whether a javascript script is present on a page or not.

Below is the html;

enter image description here

and I need to test that this is present on a particular page.

I understand that I could use Xpath (for example) and simply assert the following;

browser.assert.elementPresent('/html/head/script[10]/text()')

However, this isn’t really practical as scripts are often inserted before this script in due course which would fail the test due to the xpath of this script changing.

So, is there a way that I can pick out a certain part of this inserted javascript script (highlighted in yellow in the image above) and assert against this, rather than the whole script? This would then make the test far less brittle.

Many thanks

am trying to implement webpack dev server. so install the following package with npm express,webpack-cli. i had issue when running dev server on npm

server.get(“/”, (req, res) => {

10 | const initialMarkup = ReactDOMServer.hydrateToString();
| ^
11 |
12 | res.send(`
13 |
at Parser.pp$5.raise (C:UsersUSERAppDataRoamingnpmnode_modulesbabel-clinode_modulesbabylonlibindex.js:4454:13)
at Parser.pp.unexpected (C:UsersUSERAppDataRoamingnpmnode_modulesbabel-clinode_modulesbabylonlibindex.js:1761:8)
at Parser.pp$3.parseExprAtom (C:UsersUSERAppDataRoamingnpmnode_modulesbabel-clinode_modulesbabylonlibindex.js:3750:12)
at Parser.pp$3.parseExprSubscripts (C:UsersUSERAppDataRoamingnpmnode_modulesbabel-clinode_modulesbabylonlibindex.js:3494:19)
at Parser.pp$3.parseMaybeUnary (C:UsersUSERAppDataRoamingnpmnode_modulesbabel-clinode_modulesbabylonlibindex.js:3474:19)
at Parser.pp$3.parseExprOps (C:UsersUSERAppDataRoamingnpmnode_modulesbabel-clinode_modulesbabylonlibindex.js:3404:19)
at Parser.pp$3.parseMaybeConditional (C:UsersUSERAppDataRoamingnpmnode_modulesbabel-clinode_modulesbabylonlibindex.js:3381:19)
at Parser.pp$3.parseMaybeAssign (C:UsersUSERAppDataRoamingnpmnode_modulesbabel-clinode_modulesbabylonlibindex.js:3344:19)
at Parser.pp$3.parseExprListItem (C:UsersUSERAppDataRoamingnpmnode_modulesbabel-clinode_modulesbabylonlibindex.js:4312:16)
at Parser.pp$3.parseCallExpressionArguments (C:UsersUSERAppDataRoamingnpmnode_modulesbabel-clinode_modulesbabylonlibindex.js:3573:20) {
pos: 302,
loc: Position { line: 10, column: 55 },
_babel: true,
codeFrame: ‘x1B[0m x1B[90m 8 | x1B[39mn’ +
‘ x1B[90m 9 | x1B[39mserverx1B[33m.x1B[39mget(x1B[32m”/”x1B[39mx1B[33m,x1B[39m (reqx1B[33m,x1B[39m res) x1B[33m=>x1B[39m {n’ +

}
[nodemon] app crashed – waiting for file changes before starting…

How to display a preview value on mat-select

I am trying to create a compilation table where I have to select a value in from a mat-select.

enter image description here

In the third column I have a list of values ​​that I can choose

lunch:infoLunch[]=[{id_lunch: '',desc_lunch:''},
                     {id_lunch: 'TP1',desc_lunch:'Normale'},
                     {id_lunch: 'TP2',desc_lunch:'Senza carne'},
                     {id_lunch: 'TP3',desc_lunch:'Senza carne di maiale'},
                     {id_lunch: '14/1020',desc_lunch:'14/1020'}
  ];

And this is the html code of the column

<ng-container matColumnDef="pasto">
      <th mat-header-cell *matHeaderCellDef> Descrizione Pasto</th>
      <td mat-cell  *matCellDef="let studente">
        <mat-form-field>
          <mat-select [disabled]="studente.isAbsent || studente.isGuest" (selectionChange)="checkCheckPastovalue($event, studente)" panelClass="example-panel-dark-blue">
            <mat-option *ngFor="let cust of lunch"
                        [value]="cust"> {{studente.isAbsent || studente.isGuest ?  '': cust.desc_lunch}}
            </mat-option>
          </mat-select>
        </mat-form-field>
      </td>
    </ng-container>

I have an external json from db with set or empty values

    {
                      "idStudenti": 1,
                        "nome": "John",
                        "cognome": "Doe",
                        "isChecked": true,
                        "CodLunch": "TP1",
                        "DescLunch": "Normale",
                        "isGuest": false,
                        "hostSchool": "",
                        "isAbsent": false
                    },
                    {
                        "idStudenti": 2,
                        "nome": "Giada",
                        "cognome": "Doe",
                        "isChecked": false,
                        "CodLunch": "",
                        "DescLunch": "",
                        "isGuest": false,
                        "hostSchool": "",
                        "isAbsent": false
                    }

How can I display the current value of the json on the mat-select?

How does gql from graphql-tag works? [duplicate]

I am using graphql-tag package for graphql syntax. The syntax below I can’t understand if it is a valid javascript code.

How does it work? (Just surface level knowledge not the whole package’s working)

import gql from 'graphql-tag';

const query = gql`
  {
    user(id: 5) {
      firstName
      lastName
    }
  }

Below is the implementation of the gql from the package.

function gql(/* arguments */) {
  var args = Array.prototype.slice.call(arguments);

  var literals = args[0];

  // We always get literals[0] and then matching post literals for each arg given
  var result = literals[0];

  for (var i = 1; i < args.length; i++) {
    if (args[i] && args[i].kind && args[i].kind === 'Document') {
      result += args[i].loc.source.body;
    } else {
      result += args[i];
    }

    result += literals[i];
  }

  return parseDocument(result);
}

It seems it is a function. A function needs arguments that we pass inside parenthesis. But, gql doesn’t have any? How So?

TypeError: movieList.map is not a function, what is wrong?

import React, { useEffect, useState } from 'react';
import tmdb from './tmdb'; 
import MovieRow from './components/MovieRow';

export default () => {
  const [movieList, setMovieList] = useState([]);
  useEffect(() => {
    const loadAll = async() => {
      //Pegando a lista total
      let list = await tmdb.getHomeList();
      setMovieList(list);
    }
    loadAll();
  }, []);
  return(
    <div className="page">
      <section classname="lists">
        {movieList.map((item, key) => (
          <MovieRow/>
        ))}
      </section>
    </div>
  );
}

I’m building a clone of Netflix using React, but I’m getting this error midway into my project, can someone help me out?