How to map an API with Typescript in ReactJS?

I’m new to Typescript and I have to get a list of books from an API. My profesor gave me the code in javascript to do this, but I have to do this in typescript.

Example in Javascript

return (
            <div className="List">
                {apiData?.map(item => (
                <div className="Livro">
                    <h3> {item.name}</h3>
                    <p> {item.authors.join(',')}</p>
                    <p><a href={item.url} target='_blank' rel="noreferrer"> {item.url}</a></p>
                </div>
                ))}
            </div>
        );

I tried to do this the same way in typescript, but it return this error:

Type error: Property ‘map’ does not exist on type ‘Readonly<{}> & Readonly<{ children?: ReactNode; }>’.

Is there any way to resolve this error or another way to map an API without using map()?

Go to another page without refresh [Django]

How to achieve going to another page without refreshing after for example clicking a link to another URL. More examples, I have a list of books display and when I clicked on one of the book, it will redirect me to the selected book page. This is the example of the code link.
<a class="link" href="{% url 'books:view_book_detail' obj.book.name obj.pk %}">View book</a>

I know about the history.pushState() but how to actually use it ? Can it be use with URL from Django. Are there any method else then stated ?

foreach dentro do sweetalert2

Saudações galera,

Recebo o seguinte JSON na minha página HTML:

[
{
    "id_terminal": "1",
    "hostname": "DEV-W10PTBO1260"
},
{
    "id_terminal": "2",
    "hostname": "DEV-W10PTBO1261"
}
]

Eu queria popular meu SweetAlert2 com essas informações. Com PHP eu faria um foreach, mas em javascript e mais especificamente dentro de um SweetAlert2 não sei como, pois esses dados do JSON são muito variáveis em questão de quantidade de resultados, esse por exemplo tem somente dois, mas poderiam haver mais ou menos.

Vou tentar demonstrar qual teria que ser meu resultado:

Swal.fire({
            title: 'Terminais cadastrados',
            html: (aqui dentro teria que entrar todo o meu JSON, separado como vou demonstrar 
            no final dessa pergunta),
            showCloseButton: true,
            allowOutsideClick: false,
            showConfirmButton: false,
            })

Ali no HTML, o que teria que sair como texto plano seria:

Nome do terminal: $hostname ID do terminal: $id_terminal

Isso acima teria que ser repetido populando com todos os dados do JSON que inicialmente eu recebi.

Create a Typewriter Effect with another Variable

I am looking to make a typewriter effect using a Variable. My Variable will select a random string listed to write. I want it to list the string the same way, but i want it to use the typewriter effect to do it!

No matter where i look, i cannot find an answer on how to make the typewriter effect, it will not type the function! I want it to type a random text based on the variable! Thanks!

this is my code.

Finalising Deletion...
<progress></progress>
<!DOCTYPE html>
<html>
<body>

<br><br>

<button onclick="typeWriter()">View Status</button>

<p id="demo"></p>

<script>
var i = 0;
var txt = randomText();
var speed = 50;

function typeWriter() {
  if (i < txt.length) {
    document.getElementById("demo").innerHTML += (i);
    i++;
    setTimeout(typeWriter, speed);
  }
}
  function randomText() {
              //array splashes
              var say = [];
              say[0] = "Moving Core Files...";
              say[1] = "Deleting JavaScript";
              say[2] = "Uploading Data...";
              say[3] = "Editing HTML...";
              say[4] = "Disabling Server.js";
              say[5] = "Deleting Cookies...";
              say[6] = "Deleted Files (3/754)";
              say[7] = "Attempting URL Shutdown";
              say[8] = "Uploading Deletion Program!";
              say[9] = "Deleting URL...";
              say[10] = "Changing CSS";
              say[11] = "Deleting Inside Fules...";
             
           
              
              //pick a random greeting
              var howmany = 11;
              var bRand = 0;
              bRand = Math.random();
              bRand = Math.floor(bRand * howmany);
              //prepare and docwrite the greeting
              sayWhat = say[bRand];
              document.write(sayWhat);
              document.close();
              //direct type in html p element
              //document.getElementById("splash").innerHTML ='javascript:alert("' + '");'
              // I tried to make this work but it says no.
            }
  
</script>

</body>
</html>
  <script style="color:white" language="JavaScript" type="text/javascript">
            //script to generate random greetings
            
    </script>
    <script style="color:white" type="text/javascript">
      
    </script> 

When is the best moment to open and close the connection in Postgresql?

I’m trying to make several inserts in database from an array but … I have a problem with de connection and disconnection to the database

For example, with this code, I only insert the first element and then I’ve got an error because the access to the database has been disconnected.

async function saveData(destinations){
    let ddbb = new PostgresqlDDBB();
    ddbb.connect();
    await destinations.forEach(async (country, index) => {
        let params = [country.countryName, country.countryCode, country.urlProperties];
        let id = await ddbb.insertData(2, params);
        destinations[index].id = id;
    });
    ddbb.disconnect()
}

The object PostgresqlDDBB has this code:

import {Result} from "../../com/result";
import {clientPG} from "./pg_connection";
import {selectQuery} from "../queries/pg_queries";

class PostgresqlDDBB{
    constructor(){
        this.query = null;
    }

    set query(id){
        this.__query = selectQuery(id);
    }

    get query(){
        return this.__query;
    }

    async connect(){
        await clientPG.connect();
    }

    disconnect(){
        clientPG.end();
    }
    
    /**
     * 
     * @param {*} id_query ID of query to run
     * @param {*} params params to pass to the query
     * @returns The last id save in the database
     */
    async insertData(id_query, params){
        let result;

        try{
            let query = selectQuery(id_query);
            if (params !== null)
                result = await clientPG.query(query, params);
            else
                result = await clientPG.query(query);
            return result.rows[0].id;
        }catch(err){
            console.log(err.stack);
        }
    }
}

module.exports.PostgresqlDDBB = PostgresqlDDBB;

And the client of Postgress has this code:

import {Client} from "pg";
import config from "../../config";


    const clientPG = new Client({
        user: config.db_postgres.user,
        password: config.db_postgres.password,
        database: config.db_postgres.name,
        host: config.db_postgres.host,
        //ssl: config.db_postgres.ssl    
    });
    
    module.exports.clientPG = clientPG;

Looking for the code of saveData I don’t knwo why forEach don’t wait to finish the insert of all elements.

If I do the same instead of a forEach with a for and call the function twice:

async function saveData(destinations){
    let ddbb = new PostgresqlDDBB();
    await ddbb.connect();
    for(let i = 0; i < destinations.length; i++){
        let country = destinations[i];
        let params = [country.countryName, country.countryCode, country.urlProperties];
        let id = await ddbb.insertData(2, params);
    }
    ddbb.disconnect();
    console.log("Voy a salir!!!");
};

saveData(list);
saveData(list);

The first time works fine but the second time we’ve got this error:

Voy a salir!!!

/home/josecarlos/Workspace/BlueCode/Youmalou/mapping-service/node_modules/pg/lib/client.js:94
      const err = new Error('Client has already been connected. You cannot reuse a client.')
                  ^

Error: Client has already been connected. You cannot reuse a client.

The second time we run the function the connection is still open. How is that possible?

What is the best moment to open the connection? Is a good practive to open the connection and not close it because when the object will be deleted the connection too?

How can I open, insert data, close the connection, open connection again, insert data, close the connection etc.?

Am I doing something wrong?

EC2 Misconfiguration lead to SSL_ERROR_RX_RECORD_TOO_LONG

This problem already take days for me to search the solution. I already search in this page but only empty result.

I even don’t know where the problem starts. But the chronology is:

  1. I make Ubuntu20.04 Server t2.micro EC2 instance
  2. Only have 25GB storage
  3. Configure the security group as open as posibble like this:security config
  4. After launched, i’m installing nodejs 14.17.5
  5. run npm install
  6. My app run on port 8000.
  7. I go to my-ec2-public-ip-address:8000/ display only json message
  8. When i go to my-ec2-public-ip-address:8000/login i only get the html (no css, img, etc )

in the network tab, this is the screenshotssl_error_screenshot

but when i test the static file, for example my-ec2-public-ip-address:8000/styles/style-login.css the server returning correct css file.

if you want to see the source-code, let me know in the comment, because i don’t think it will help much. Because my guess is the problem exist on the server configuration. When run locally, everything normal

How to creat an array that includes multiples elements from an object from the local Storage

I would like to creat an array that includes every products id’s from the local storage object of my shopping website cart. The thing is the function that i made generate an array for each product’s id instead of one array with all the product’s id in it

 var cartStorage = JSON.parse(localStorage.getItem("cart"));
        cartStorage.forEach(function (cart, index) {
        let cartIds = [cart._id];
        console.log(cartIds); // logs one array for each id instead of just one array with every id's
       });

I’ve been trying for hours but nothing seems to work, i’m guessing i have to use a forEach() but i can’t make that work?

VirtualizedList onViewableItemsChanged not update lasted props value

I’m facing this issue in Android with ReactNative.

My application have a button with onPress event and VirtualizedList with onViewableItemsChanged event. Both events call a function named aa() that print out props.activeTabKey value to console.

  1. When application launched the props.activeTabKey are set to “AA”. Both events print “AA” to console, that’s good.
  2. When i change the props.activeTabKey to “BB”. The onPress event print “BB”, but the onViewableItemsChanged still print “AA”.
  3. Next, I change props.activeTabKey to “CC”. The onPress event print “CC” and the onViewableItemsChanged print “BB”.

It’s look like onViewableItemsChanged event not see the last value of props. I have change the aa() function to use useCallback(), but the issue still happend.

Please help me to resolve this. Thanks in advance.
enter image description here

getUserMedia – camera vertical stream

I have a problem with streaming from the camera in app. I used webrtc and simple-peer in the project. Project work well but when I would use a camera (Logitech streamcam) as a vertical cam, the stream has black bars on the left and right side. Ultimately app has to work on 2 devices:
1 – vertical screen with a horizontal stream
2 – horizontal screen with a vertical stream
Some ideas, how to get a vertical stream without black bars?
When I use the front camera from the phone work perfectly…

/**
 * UserMedia constraints
 */
let constraints = {
    audio: true,
    video: true,
}
/////////////////////////////////////////////////////////

constraints.video.facingMode = {
    ideal: "user"
}

// enabling the camera at startup
navigator.mediaDevices.getUserMedia(constraints).then(stream => {

    localVideo.srcObject = stream;
    localStream = stream;

    init()

}).catch(e => alert(`getusermedia error ${e.name}`))

rollup output js files into folder

So i have this project where i will have a lot of components i want to output those into a build/components however i can’t seem to get it right:

My rollup file

import html from '@web/rollup-plugin-html';
import {copy} from '@web/rollup-plugin-copy';
import resolve from '@rollup/plugin-node-resolve';
import {terser} from 'rollup-plugin-terser';
import minifyHTML from 'rollup-plugin-minify-html-literals';
import summary from 'rollup-plugin-summary';

export default {
    plugins: [
        // Entry point for application build; can specify a glob to build multiple
        // HTML files for non-SPA app
        html({
            input: 'index.html',
        }),
        // Resolve bare module specifiers to relative paths
        resolve(),
        // Minify HTML template literals
        minifyHTML(),
        // Minify JS
        terser({
            ecma: 2020,
            module: true,
            warnings: true,
        }),
        // Print bundle summary
        summary(),
        // Optional: copy any static assets to build directory
        copy({
            patterns: ['images/**/*'],
        }),
    ],
    output: {
        dir: 'build',
    },
    preserveEntrySignatures: 'strict',
};

This outputs all of my files in the root next to the index.html with a seperate asset folder for some of the polyfills.

But how can i ensure that all my javascripts goes into a components folder?

Nest can’t resolve dependencies of the TypeOrmCoreModule

src/contact/contact.module.ts

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ContactController } from './contact.controller';
import { Contact } from './contact.entity';
import { ContactRepository } from './contact.repo';
import { ContactService } from './contact.service';

@Module({
  imports: [
     TypeOrmModule.forFeature([
      Contact,
    ]), 
  ],
  controllers: [ContactController],
  providers: [ContactService, ContactRepository],
})
export class ContactModule {}

src/app.module.ts

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { getMetadataArgsStorage } from 'typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ContactModule } from './contact/contact.module';

@Module({
  imports: [
   TypeOrmModule.forRoot({
      type: 'sqlite',
      database: 'db',
      entities: getMetadataArgsStorage().tables.map(tbl => tbl.target),
      synchronize: true,
    }), 
    ContactModule
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

npm new start:dev

Give this kind of error where I try to find possibly every solution on the internet but what mistake I’m doing I don’t know, I got an error like.

nest -v (8.1.6)

ERROR [ExceptionHandler] Nest can't resolve dependencies of the TypeOrmCoreModule (TypeOrmModuleOptions, ?). Please make sure that the argument ModuleRef at index [1] is available in the TypeOrmCoreModule context.

Potential solutions:
- If ModuleRef is a provider, is it part of the current TypeOrmCoreModule?
- If ModuleRef is exported from a separate @Module, is that module imported within TypeOrmCoreModule?
  @Module({
    imports: [ /* the Module containing ModuleRef */ ]
  })

Changing css class with classList.add not working

I wanna add a class that makes a button looks disabled with calssList.add, I’m having hard time snice yesterday with this since i can’t see any difference on the button, even if i see in the inspector that the button is having the css class that i wanna add, it doesn’t make any changes.

                    alert("You can't have more than two articles in this layout");
                    saveButton.disabled = true;
                    saveButton.classList.add("fl-button-disabled"); ```


//css

 .fl-settings-save.fl-button.fl-button-large.fl-button-disabled{
    pointer-events: none;
    color: #666666;
    background-color: gray;
    border: 1px solid gray;
}


Complex string manipulation by JavaScript regexp

I am generating some meaningful name with the following rule in a JavaScript/Node JS program:

Input: “tenancy_account__accountPublicId__workspace__workspacePublicId__remove-user__userPublicId

Expected output: “TenancyAccountAccountPublicIdWorkspaceWorkspacePublicIdRemove-userUserPublicId”

Rules:

  1. replace any character with zero or more underscore to the non-underscored uppercase
    Example:x | __*x => X
  2. If exists remove last _

This is what is tried so far, looking for better alternatives, if any:

const convertBetterString = (input) => {
    const finalString = [];
    if (input && input.includes('_')) {
        const inputStringSeparation = input.split('_');
        if (inputStringSeparation.length > 1) {
            if (inputStringSeparation[inputStringSeparation.length - 1] === '') {
                inputStringSeparation.splice(inputStringSeparation.length - 1, 1);
            }
            inputStringSeparation.forEach((val, index) => {
                if (val === '' && inputStringSeparation[index + 1]) {
                    const actualString = inputStringSeparation[index + 1];
                    const formattedString = actualString.charAt(0).toUpperCase() + actualString.slice(1);
                    finalString.push(formattedString);
                }
            });
            return finalString.length > 0 ? finalString.join('') : inputStringSeparation.join('');
        } else {
            return input.charAt(0).toUpperCase() + input.slice(1);
        }
    } else {
        return input;
    }
}

ochange event only works after the second selection

I have to show some data base on selection drop down list, the form is dynamic, here is my teplates

        function imeiInfo () {    
            $('select').change(function(e) {
                e.stopImmediatePropagation();
                let elm = $(this);
                data = {};
                data[elm.attr("name")] = elm.val();
                $.ajax({
                    url:'/ajax/return_back_imei_plusinfo/',
                    data:data,
                    success:function(data){
                        console.log(data.price)
                        if (data.price){
                            elm.closest("div.child_imeiforms_row").find("input.nrx").val(data.price);
                        }

                        if (data.mobile){
                            elm.closest("div.child_imeiforms_row").find("input.mobile-type").val(data.mobile);
                        }
                    }
                })
            })             
        }
        imeiInfo();
        <form action="" method="POST" id="create-permcustomer-invoice">{% csrf_token %}        
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                    <i class="fas fa-file-signature"></i>
                    <label>customer</label>
                    {{ main_form.customer | add_class:'form-control' }}
                    </div>
                    <p class="text-danger text-center" hidden id="collection_date_error"></p>
                </div>
                <div class="col-md-2">
                    <div class="form-group">
                    <i class="fas fa-box-usd"></i>                        
                    <label>balance</label>
                    <input type="number" disabled class="form-control" id="balance_cus">

                </div>
                    <!-- /.form-group -->
                </div>               
                <!-- /.col -->
                <div class="col-md-4 pull-right">
                    <div class="form-group">
                    <i class="far fa-clock"></i>
                    <label>date</label>
                    {{main_form.created | add_class:'form-control text-center'}}
                    </div>
                    <p class="text-danger text-center" hidden id="company_error"></p>
                    <!-- /.form-group -->
                </div>                 
            </div>   
            <div class="row no-gutters title_info text-center table-bordered text-white">
            </div>         
            {{imei_forms.management_form}}
            <div id="form-imeilists">
                {% for imei in imei_forms %}
                {{imei.id}}
                <div class="child_imeiforms_row">

                    <div class="row no-gutters table-bordered">
                        <div class="col-md-3">
                            <div class="form-group">
                                {{imei.item | add_class:'form-control choose'}}
                                <div class="text-danger text-center" hidden></div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <input type="text" disabled class="form-control mobile-type" placeholder='mobile type '>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                {{imei.price | add_class:'nrx'}}
                                <div class="text-danger text-center" hidden></div>
                            </div>
                        </div>
                        <div class="col-md-1">
                            <div class="form-group">
                                {{imei.discount | add_class:'dis'}}
                                <div class="text-danger text-center" hidden></div>
                            </div>
                        </div>                                                
                        <div class="col-md-2">
                            <div class="form-group">
                                {{imei.cash | add_class:'cash'}}
                                <div class="text-danger text-center" hidden></div>
                            </div>
                        </div>
                {% endfor %}
            </div>
            <div id="empty-imei-invoiceform" class="hidden">
                <div class="row no-gutters table-bordered">
                    <div class="col-md-3">
                        <div class="form-group">
                            {{imei_forms.empty_form.item | add_class:'form-control choose'}}
                            <div class="text-danger text-center" hidden></div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <input type="text" disabled class="form-control mobile-type" placeholder='mobile type'>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            {{imei_forms.empty_form.price | add_class:'nrx'}}
                            <div class="text-danger text-center" hidden></div>
                        </div>
                    </div>
                    <div class="col-md-1">
                        <div class="form-group">
                            {{imei_forms.empty_form.discount | add_class:'dis'}}
                            <div class="text-danger text-center" hidden></div>
                        </div>
                    </div>                                                
                    <div class="col-md-2">
                        <div class="form-group">
                            {{imei_forms.empty_form.cash | add_class:'cash'}}
                            <div class="text-danger text-center" hidden></div>
                        </div>
                    </div>
            <button type="button" class="btn btn-lg btn-info" id="add-more-invoice">add new row</button>

            <div class="card-footer">
                <div class="row justify-content-center">
                    <button type="submit" class="btn btn-lg btn-success">save</button>
                </div>
            </div>
        </form>

but it only works well for the first form, after the form, i’ve to select the drop down list in order to return the data !
and here is my views.py

@login_required
def return_back_imei_plusinfo(request):
    query = request.GET
    for item in query:
        if item.startswith("imei-") and item.endswith("-item"):
            item_id = query.get(item)
            break    
    selling_price= Imei.objects.get(id=item_id).mobile.selling_price,
    mobile=Imei.objects.get(id=item_id).mobile.mobile.model,
data = {
    'price' : selling_price,
    'mobile':mobile,
}    
return JsonResponse(data)

and here is my forms.py

class ImeiModelChoiceField(ModelChoiceField):
    def label_from_instance(self,obj):
         return str(obj.imei)

class ImeiInvoiceForm(forms.ModelForm):
    item = ImeiModelChoiceField(queryset=Imei.objects.filter(status=True),widget=forms.Select(attrs={'onchange':'imeiInfo();'}))
    class Meta:
        model = ImeiInvoice
        fields = ['item','price','cash','discount']
        widgets = {
            'price':forms.NumberInput(attrs={'class':'form-control','onkeyup':'totalSum()'}),
            'cash':forms.NumberInput(attrs={'class':'form-control','onkeyup':'totalSum()'}),
            'discount':forms.NumberInput(attrs={'class':'form-control','onkeyup':'totalSum()'}),

    }

is there another way achieve that please !?
thank you in advance ..

How to throw a server error when fetching JS

I’m new in JavaScript and i have a task to post an email input from form to a node server,everything works fine,but i should implement this functionality:
When an email is [email protected], the server responds with the 422 status code and payload which contains the information about the error. Use browser developer tools to examine the response for this scenario. Display the error message in the browser using window.alert().
I created a customException,it gives me the error in the console,but the server still responds with the 200 status code,but as i understand,it should give an error and the post should not work.How to do this task,i have no idea..?
Fetch functions:

import { validateEmail } from './email-validator.js'

export const sendSubscribe = (emailInput) => {
    const isValidEmail = validateEmail(emailInput)
    if (isValidEmail === true) {
        sendData(emailInput);
        // if (emailInput === '[email protected]'){
        //     throw new CustomException('422');
        // }
    }
}

const sendHttpRequest = (method, url, data) => {
    return fetch(url, {
        method: method,
        body: JSON.stringify(data),
        headers: data ? {
            'Content-Type': 'application/json'
        } : {}
    }).then(response => {
        if (response.status >= 400) {
            return response.json().then(errResData => {
                const error = new Error('Something went wrong!');
                error.data = errResData;
                throw error;
            });
        }
        return response.json();
    });
};

const sendData = (emailInput) => {
    sendHttpRequest('POST', 'http://localhost:8080/subscribe', {
        email: emailInput
    }).then(responseData => {
        console.log(responseData);
    }).catch(err => {
        console.log(err, err.data);
    });
}

function CustomException(message) {
    const error = new Error(message);
    error.code = "422";
    window.alert('Forbidden email,please change it!')
    return error;
  }
  
  CustomException.prototype = Object.create(Error.prototype);

Validate function:

const VALID_EMAIL_ENDINGS = ['gmail.com', 'outlook.com', 'yandex.ru']

export const validateEmail = (email) => !!VALID_EMAIL_ENDINGS.some(v => email.includes(v))

export { VALID_EMAIL_ENDINGS as validEnding }

Please help.Thanks in advance!