reactjs – New Repository unexpectedly adds other files

I created a new repository for my first create-react-app and when I went to setup the remote connection to my github repository it failed. After going to my github repository I found files and even entire repositories had been added to both my local and Github repository, but they are not visible in my editor or desktop folder. If anyone could at least point me in the right direction as to what happened and how I can resolve this I would greatly appreciate it. Here is what I see when I run git status after attempting to push changes to my github repository:

cam@Anduril  ~/Desktop/starting-react   Master ●  git status
On branch Master
Changes not staged for commit:
(use “git add/rm …” to update what will be committed)
(use “git restore …” to discard changes in working directory)
modified: ../.DS_Store
deleted: ../Budget/css/all.css
deleted: ../Budget/css/bootstrap.min.css
deleted: ../Budget/css/main.css
deleted: ../Budget/index.html
deleted: ../Death Knell/deathknell.css
deleted: ../Death Knell/deathknell.html
deleted: ../Death Knell/deathknellabout.css
deleted: ../Death Knell/deathknellabout.html
deleted: ../Death Knell/deathknellcontact.css
deleted: ../Death Knell/deathknellcontact.html
deleted: ../Death Knell/deathknellmusic.css
deleted: ../Death Knell/deathknellmusic.html
deleted: ../Death Knell/deathknellshows.css
deleted: ../Death Knell/deathknellshows.html
deleted: ../READ.md
modified: ../color-game/index.html
modified: ../color-game/index.js
modified: ../color-game/styles.css
deleted: ../deathknell.htm
deleted: ../deathknell/.DS_Store
deleted: ../deathknell/amazonmusic.png
deleted: ../deathknell/bandcamp.png
deleted: ../deathknell/deathknell.css
deleted: ../deathknell/deathknell.html
deleted: ../deathknell/deathknellabout.css
deleted: ../deathknell/deathknellabout.html
deleted: ../deathknell/deathknellcontact.css
deleted: ../deathknell/deathknellcontact.html
deleted: ../deathknell/deathknellmusic.css
deleted: ../deathknell/deathknellmusic.html
deleted: ../deathknell/deathknellshows.css
deleted: ../deathknell/deathknellshows.html
deleted: ../deathknell/dkbackground.jpg
deleted: ../deathknell/dklanding.jpg
deleted: ../deathknell/facebook.png
deleted: ../deathknell/insta.png
deleted: ../deathknell/itunes.png
deleted: ../deathknell/logo.png
deleted: ../deathknell/spotify.png
deleted: ../deathknell/twitter.png
deleted: ../deathknell_files/41uN8iSe7gL.SX301_BO1,204,203,200.jpg
deleted: ../deathknell_files/Digital-Identity-Unpacked-1.png
deleted: ../deathknell_files/api.js
deleted: ../deathknell_files/app.html
deleted: ../deathknell_files/cb=gapi(1).loaded_0
deleted: ../deathknell_files/cb=gapi.loaded_0
deleted: ../deathknell_files/death-of-liberty.jpg
deleted: ../deathknell_files/email_grey600_24dp.png
deleted: ../deathknell_files/fb_32x32.png
deleted: ../deathknell_files/googlelogo_color_92x30dp.png
deleted: ../deathknell_files/images
deleted: ../deathknell_files/images(1)
deleted: ../deathknell_files/images(10)
deleted: ../deathknell_files/images(11)
deleted: ../deathknell_files/images(12)
deleted: ../deathknell_files/images(13)
deleted: ../deathknell_files/images(14)
deleted: ../deathknell_files/images(15)
deleted: ../deathknell_files/images(16)
deleted: ../deathknell_files/images(17)
deleted: ../deathknell_files/images(18)
deleted: ../deathknell_files/images(19)
deleted: ../deathknell_files/images(2)
deleted: ../deathknell_files/images(20)
deleted: ../deathknell_files/images(21)
deleted: ../deathknell_files/images(22)
deleted: ../deathknell_files/images(23)
deleted: ../deathknell_files/images(24)
deleted: ../deathknell_files/images(25)
deleted: ../deathknell_files/images(26)
deleted: ../deathknell_files/images(27)
deleted: ../deathknell_files/images(28)
deleted: ../deathknell_files/images(29)
deleted: ../deathknell_files/images(3)
deleted: ../deathknell_files/images(30)
deleted: ../deathknell_files/images(31)
deleted: ../deathknell_files/images(32)
deleted: ../deathknell_files/images(33)
deleted: ../deathknell_files/images(34)
deleted: ../deathknell_files/images(35)
deleted: ../deathknell_files/images(36)
deleted: ../deathknell_files/images(37)
deleted: ../deathknell_files/images(38)
deleted: ../deathknell_files/images(39)
deleted: ../deathknell_files/images(4)
deleted: ../deathknell_files/images(40)
deleted: ../deathknell_files/images(41)
deleted: ../deathknell_files/images(42)
deleted: ../deathknell_files/images(43)
deleted: ../deathknell_files/images(44)
deleted: ../deathknell_files/images(45)
deleted: ../deathknell_files/images(46)
deleted: ../deathknell_files/images(47)
deleted: ../deathknell_files/images(48)
deleted: ../deathknell_files/images(49)
deleted: ../deathknell_files/images(5)
deleted: ../deathknell_files/images(50)
deleted: ../deathknell_files/images(51)
deleted: ../deathknell_files/images(52)
deleted: ../deathknell_files/images(53)
deleted: ../deathknell_files/images(54)
deleted: ../deathknell_files/images(55)
deleted: ../deathknell_files/images(56)
deleted: ../deathknell_files/images(57)
deleted: ../deathknell_files/images(58)
deleted: ../deathknell_files/images(59)
deleted: ../deathknell_files/images(6)
deleted: ../deathknell_files/images(60)
deleted: ../deathknell_files/images(61)
deleted: ../deathknell_files/images(62)
deleted: ../deathknell_files/images(63)
deleted: ../deathknell_files/images(64)
deleted: ../deathknell_files/images(65)
deleted: ../deathknell_files/images(66)
deleted: ../deathknell_files/images(67)
deleted: ../deathknell_files/images(68)
deleted: ../deathknell_files/images(69)
deleted: ../deathknell_files/images(7)
deleted: ../deathknell_files/images(70)
deleted: ../deathknell_files/images(71)
deleted: ../deathknell_files/images(72)
deleted: ../deathknell_files/images(73)
deleted: ../deathknell_files/images(74)
deleted: ../deathknell_files/images(75)
deleted: ../deathknell_files/images(76)
deleted: ../deathknell_files/images(77)
deleted: ../deathknell_files/images(78)
deleted: ../deathknell_files/images(79)
deleted: ../deathknell_files/images(8)
deleted: ../deathknell_files/images(80)
deleted: ../deathknell_files/images(81)
deleted: ../deathknell_files/images(82)
deleted: ../deathknell_files/images(83)
deleted: ../deathknell_files/images(84)
deleted: ../deathknell_files/images(85)
deleted: ../deathknell_files/images(86)
deleted: ../deathknell_files/images(87)
deleted: ../deathknell_files/images(88)
deleted: ../deathknell_files/images(89)
deleted: ../deathknell_files/images(9)
deleted: ../deathknell_files/images(90)
deleted: ../deathknell_files/images(91)
deleted: ../deathknell_files/m=BuhrE,GxIAgd,MkHyGd,NpD4ec,OG6ZHd,PygKfe,RI5Krb,RqxLvf,T6sTsf,T7XTS,URQPYc,Wq6lxf,XjCeUc,aa,aam1T,async,eN4qad,ebqyud,fEVMic,foot,lazG7b,m,mI3LFb,mUpTid,mu,o02Jie,pB6Zqd,qZ1Udb,qi,qik19b,rHjpXd,sb_wiz,sf,sonic,spch,str,uiNkee,ujFhWe,wft,wkrYee,xz7cCd,zb
deleted: ../deathknell_files/m=FBWYne,mfkHA,ptS8Ie
deleted: ../deathknell_files/m=GSWAyf,XeLme
deleted: ../deathknell_files/m=Q7Rsec,d0xvhc
deleted: ../deathknell_files/m=_b,_tp
deleted: ../deathknell_files/m=qOaBwc
deleted: ../deathknell_files/m=sYcebf
deleted: ../deathknell_files/rs=AA2YrTs9lXdWY2A2Qw-5oWtGGTmrLlgIag
deleted: ../deathknell_files/rs=AA2YrTsqFA6Alk0U0hqoEHSxPPrr1CyLow
deleted: ../deathknell_files/rs=ACT90oGYE-hpqRt5BryEYHWoW-CQS2_X6A
deleted: ../deathknell_files/spin-24.gif
deleted: ../deathknell_files/twitter_32x32.png
deleted: ../html:css/acme.css
deleted: ../html:css/acme.html
deleted: ../html:css/index.css
deleted: ../html:css/index.html
deleted: ../html:css/jsexercises.js
deleted: ../html:css/sample.jpg
deleted: ../html:css/survey.css
deleted: ../html:css/survey.html
deleted: ../html:css/tribute.css
deleted: ../html:css/tribute.html

Untracked files:
(use “git add …” to include in what will be committed)
../.gitignore
../ArtsTaxReceipt.pdf
../Bootstrap 4/
../Bootstrap v3 practice/
../CS101.pdf
../CSS Grid Cardio/
../DeveloperResume.pdf
../FMG Suite Resume.pdf
../Frontend Mentor/
../Javascript Practice/
../Matt Garstka/
../MyShop/
../Patatap/
../Portfolio/
../TaxReturn.pdf
../Todo-list/
../acmeinner.html
../back/
../beginner-javascript-master/
../binarynotes.pdf
../color-game/README.md
../data_structures/
../deathknellv2/
../fontawesome-free-5.13.0-desktop/
../fontawesome-free-5.13.0-web/
../html5up-read-only/
../html5up-solid-state/
../html:css/Bear.jpg
../html:css/IMG_4429.HEIC
../html:css/blog.css
../html:css/blog.html
../html:css/cssbasics.html
../html:css/debug.css
../html:css/html.png
../html:css/intro.html
../html:css/photoblog.html
../html:css/photos.css
../html:css/reset.css
../html:css/selectors.css
../html:css/technicaldoc.css
../html:css/technicaldoc.html
../mealpan ebook.pdf
../mongodb-macos-x86_64-4.4.0/
../photos.css
./

no changes added to commit (use “git add” and/or “git commit -a”)
cam@Anduril  ~/Desktop/starting-react   Master ● 

reactjs – Custom Hook prevenir returns innecesarios si no se ha procesado a un estado

Tengo un custom hook, el cual se encarga de resolver mi archivo de multilenguaje, pero al instanciar mi hook dentro de mi componente funcional, no se resuelve a la primera, es decir, tarda el resolver la data, enviando por primera ves un objeto vacio. Hay una forma de que mi hook, sea preziso y solo me regrese directamente la información de una?

introducir la descripción de la imagen aquí

useTranslate.jsx

import React, { useEffect, useContext, useState } from 'react';
import { I18nContext } from 'locale/locale';

    export default function useTranslate(domain) {
      const { langCode } = useContext(I18nContext);
      const (trans, setTranslation) = useState({});
    
      useEffect(() => {
            const translation = async () => {
                const transFile = await import(`domain/${domain}/translation`);
                if (transFile) {
                    const translation = transFile(langCode);
                    setTranslation(translation);
                }
            }
            translation();
        }, (domain, langCode));
    
        return trans;
    }

Entiendo el comportamiento de useEffect, y se que entra en acción despues de el renderizado, es decir, como lo tengo ahora siempre enviara {} Que me recomiendan para prevenir eso?

const data = useTranslate('talents');

reactjs – I want to write test case for the below one

I want to write the unit-test cases for this. I am new to React .Any help would be appreciated.

class AddAndRemoveButtons extends React.Component {
    state =
        {
          showForm: false,
          shouldShowButton: true,
        }

    showForm = () => (
      <div>
        <form id="add-app">
          <div>
            <tr>
              <textarea name="InputTextArea" placeholder="Add" />
              <SaveAndCancelButton />
            </tr>
          </div>
        </form>
      </div>
    )

    render() {
      const show = this.state.shouldShowButton;
      if (show) {
        return (
          <span>
            <td>
              <button
                variant="secondary"
                onClick={() => { this.setState({ showForm: true });
                  this.setState({ shouldShowButton: false });
                }}
              >
                Add 
              </button>
            </td>
            <button
              variant="secondary" onClick={() => { this.setState({ showForm: true });
                this.setState({ shouldShowButton: false });
                }}>Remove</button>
            {this.state.showForm ? this.showForm() : null}
          </span>
        );
      }
      return (
        this.showForm()
      );
    }
}
export default AddAndRemoveButtons;

reactjs – Cancel all subscriptions and asynchronous tasks without use useEffect, must be in handleSubmit

Good afternoon everyone, I need a solution to a problem in my Front side application with REACT, about a problem that I have not been able to solve so far after many attempts to search, said problem has to do with the life cycle of the components that It is handled in react in this case for React Hooks for functional components, I have a module where I make a payment with the Striper library, I also use another library called Stepper and others, but these are the important ones ,,,

The sequence starts like this:
In step 1 I confirm the payment,
In step 2 I select the payment method
In step 3 the payment must be made first I must fill in all the data in a form such as: name of the holder, email, card number and other fields more ,,, when I click on the button I verify that all the fields are filled and are valid once all is well just starting to create the payment through code extracted from the Stripe documentation, the issue is that these calls are made through asynchronous requests with async and await, when I verify that the call was made correctly and I receive an answer I will just go to the last step of the Stepper which would be step 4 so I will have to change to another new component where I will show a Success message for the payment made correctly and the previous component disappear, but when I change to this new component I receive this error :

Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

I have already investigated enough applying different solutions for different pages even in stackoverflow, but all the examples that I see always use the useEffect to perform actions when mounting or unmounting the component either to subscribe or unsubscribe and cancel async calls with fetch, but in my case not I must use the useEffect because it does not apply to my case, I need to clean everything in the handleSubmit, I repeat that I have already applied a variety of solutions but none have worked for me

Here I leave my summarized code

here delete code of several state variables, just leave the state variables of the stepper when state change updating on a number


const useStateGlobal = () => {
    const (steps) = useState(
        ({
            title: 'Confirmar Compra',
            href: 'http://example1.com',
            onClick: (e) => {
                e.preventDefault()
                console.log('onClick', 1)
            }
        }, {
            title: 'Seleccionar tipo de pago',
            href: 'http://example2.com',
            onClick: (e) => {
                e.preventDefault()
                console.log('onClick', 2)
            }
        }, {
            title: 'Detalles de pago',
            href: 'http://example3.com',
            onClick: (e) => {
                e.preventDefault()
                console.log('onClick', 3)
            }
        }, {
            title: 'Compra Finalizada',
            href: 'http://example4.com',
            onClick: (e) => {
                e.preventDefault()
                console.log('onClick', 4)
            }
        })
    );

    const (currentStep, setCurrentStep) = useState(0);
   
    return {
        steps,
        currentStep,setCurrentStep
    }
};
export const Confirmar_Paquete_Stepper = () => {  
        
        const { steps, currentStep, setCurrentStep } = useBetween(useStateGlobal);
        const buttonStyle = { background: '#E0E0E0', width: 200, padding: 16, textAlign: 'center', 
        margin: '0 auto', marginTop: 32 };

        const onClickNext = (e) => {           
            let valor = (currentStep == null || currentStep == 0 )  ? 1 : currentStep+1;           
            setCurrentStep(valor);
        }

         const onClickBack = (e) => {
             let valor = (currentStep == null || currentStep == 0) ? 1 : currentStep - 1;
             setCurrentStep(valor);
         }

        if (currentStep == 0) {
        return (           
               <div id="contenedor-stepper-compra-paquete"> 
                   <Stepper steps={steps} activeStep={currentStep}  />
                <Confirmar_Paquete />
               </div>
        );
        }
        else if (currentStep == 1) {
        return (
               <div id="contenedor-stepper-compra-paquete">
                   <Stepper steps={steps} activeStep={currentStep} />
                   <Seleccionar_Tipo_Pago_Paquete />     
                <div style={buttonStyle} onClick={onClickBack}>Volver</div>
               </div>
        );
        } else if (currentStep == 2) {
            return (
                <div id="contenedor-stepper-compra-paquete">
                    <Stepper steps={steps} activeStep={currentStep}  />

                  these are the components that create the inputs of the card number, expiration 
                  date, cvc and process and create the card payment method with the Stripe library

                    <Elements stripe={stripePromise}>
                        <CheckoutForm2/>
                    </Elements>
                    <div style={buttonStyle} onClick={onClickBack}>Volver</div>
                </div>
        );
        }   
          else if (currentStep == 3) {
              return (
                  <div id="contenedor-stepper-compra-paquete">
          
                      <Stepper steps={steps} activeStep={currentStep}  />
                      <Finalizar_Compra_Paquete />
                      <div style={buttonStyle} onClick={onClickBack}>Volver</div>
                  </div>
            );
        }  
};
 const CheckoutForm2 = () => {    
    const { steps, currentStep, setCurrentStep, token, datos_paquete_seleccionado, setDatos_paquete_seleccionado, camposDatosTarjeta, setcamposDatosTarjeta, formErrors, setformErrors, errores_servTarjeta, seterrores_servTarjeta,
            paseValidacionFormTitularTarjeta, setpaseValidacionFormTitularTarjeta,
            paseValidacionFormCorreoTarjeta, setpaseValidacionFormCorreoTarjeta,
            paseValidacionFormTarjeta, setpaseValidacionFormTarjeta,
            paseValidacionFormFechaExpTarjeta, setpaseValidacionFormFechaExpTarjeta,
            paseValidacionFormCvcTarjeta, setpaseValidacionFormCvcTarjeta,
            paseValidacionFormCiudadTarjeta, setpaseValidacionFormCiudadTarjeta,
        paseValidacionFormCodigoPostalTarjeta, setpaseValidacionFormCodigoPostalTarjeta
       } = useBetween(useStateGlobal);
    const stripe = useStripe();
    const elements = useElements();
    const titularTarjetaRegex = RegExp(
        /^(A-Za-zs)+$/
    );
    const emailRegex = RegExp(
        /^(a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-)+@(a-zA-Z0-9-)+(?:.(a-zA-Z0-9-)+)*$/
    );
    const codigopostalTarjetaRegex = RegExp(
        /^(0-9)+$/
    );
    const ciudadTarjetaRegex = RegExp(
        /^(A-Za-z)+$/
    );

    
    useEffect(() => {
        return () => {
            
        };
    }, ());

    const HandleValidar = async (event) => {
          Here I have code only to validate the form fields by OnChange, I have deleted it because they 
          are not important
    }

    const handleSubmit = async (event) => {
       
        event.preventDefault();        
        const { titular_tarjeta, correo_tarjeta, ciudad_tarjeta, codigo_postal_tarjeta } = event.target;  
        
Here I leave only an example of how valid each field of my form when I click directly on handleSubmit by onClick,

        //TITULAR TARJETA
        if (titular_tarjeta.value.length < 3) {           
            setformErrors(prevState => ({ ...prevState, titular_tarjeta: "Ingrese mínimo 3 caracteres"
         }));
            seterrores_servTarjeta(prevState => ({ ...prevState, titular_tarjeta: "" }));
            setpaseValidacionFormTitularTarjeta("NO");            
        }
        else if (!titularTarjetaRegex.test(titular_tarjeta.value)) {            
            setformErrors(prevState => ({ ...prevState, titular_tarjeta: "Formato de nombres inválido" 
         }));
            seterrores_servTarjeta(prevState => ({ ...prevState, titular_tarjeta: "" }));
            setpaseValidacionFormTitularTarjeta("NO");
            
        }
        else if (titular_tarjeta.value.length > 22) {
            setformErrors(prevState => ({ ...prevState, titular_tarjeta: "Ingrese maximo 22 caracteres" 
        }));
            seterrores_servTarjeta(prevState => ({ ...prevState, titular_tarjeta: "" }));
            setpaseValidacionFormTitularTarjeta("NO");
        }
        else {
            setformErrors(prevState => ({ ...prevState, titular_tarjeta: "" }));
            seterrores_servTarjeta(prevState => ({ ...prevState, titular_tarjeta: "" }));
            setpaseValidacionFormTitularTarjeta("SI");            
        }

        

        if (!stripe || !elements) {
            // Stripe.js has not yet loaded.
            // Make sure to disable form submission until Stripe.js has loaded.
            return;
        }
        
        Here I validate through a set of each state that all the fields have been completed and validated 
        correctly to just start creating the payment


        if (paseValidacionFormTitularTarjeta == "SI" && paseValidacionFormCorreoTarjeta == "SI" && paseValidacionFormTarjeta == "SI" && paseValidacionFormFechaExpTarjeta == "SI" && paseValidacionFormCvcTarjeta == "SI" && paseValidacionFormCiudadTarjeta == "SI" && paseValidacionFormCodigoPostalTarjeta == "SI")
        {    
            const cardElement = elements.getElement(CardNumberElement);

            const { error, paymentMethod } = await stripe.createPaymentMethod({
                type: 'card',
                card: cardElement,
                billing_details: {
                    email: camposDatosTarjeta.correo_tarjeta,
                    name: camposDatosTarjeta.titular_tarjeta,
                    address: {
                        city: camposDatosTarjeta.ciudad_tarjeta,
                        country: 'PE',
                        postal_code: camposDatosTarjeta.codigo_postal_tarjeta,
                    }
                },               
            });

            if (error) {                
            } 
            else 
            {     

This is when once I verify that the stripe filled the variables without error, I just update setCurrentStep to 3 which would be the last step, but when I do this I remove the current component from CheckoutForm2 receiving the error ,,, this is caused by await ,, ,
since if I delete this code and direct setCurrentStep to 3, the error no longer appears ,,,
     
               setCurrentStep(3);                   
            }
        }
    };

    return (
        <div id="contenedor-detalles-tarjeta">
            <Container component="main" maxWidth="md" justify="center">
                <label className="detalles-tarjeta-titulo">
                <Typography >
                    <span >Detalles de tarjeta</span>
                </Typography>
            </label>
            <form id="realizar-pago-visa" onSubmit={handleSubmit} noValidate>

           Here I have deleted all the code of the creation of the fields of the payment form, I have 
           only left the handleSubmit button

         <Button type="submit" className="confirmar-orden" name="confirmar_orden" disabled= 
         {!stripe} variant="contained" color="primary">Confirmar orden</Button> 
         </form>
         </Container>
        </div>
    );
}

so I need to know how to unsubscribe and clean up all the asynchronous tasks such as await so that when changing components I no longer receive the error ,,,, all this I must do from my handleSubmit function, the use of useEffect is not applicable for my case, ,,

reactjs – Render paypal into existing button

I am integrating paypal into my website. I followed instructions on their documentation and everything is working fine except part that I must use paypal button for rendering.
So is it possible to render paypal on my existing button instead of creating new one?

 async function showPaypal(values, order) {
    
         let chargeamount= numformat((Number(user.deliverycost)))
      

        setShowpaypal(true)

        window.paypal.Buttons({
            createOrder: function (data, actions) {
                // This function sets up the details of the transaction, including the amount and line item details.
                return actions.order.create({
                    purchase_units: ({
                        amount: {
                            value: chargeamount
                        }
                    })
                });
            },
            onApprove: function (data, actions) {
                // This function captures the funds from the transaction.
                
                return actions.order.capture().then(async function (details) {
                    // This function shows a transaction success message to your buyer.

                     navigate("/done?order=" + order);

                    // alert('Transaction completed by ' + details.payer.name.given_name);
                });
            }
        }).render('#paypal-button-container');

    }

Then I want to render it when user click on pay button

 <Button
                    className="primary-button"
                    variant="contained"
                    type="submit"
                    size="medium"
                    color="primary"
                    style={{height: "60px"}}
                   id="paypal-button-container"
                >
                      Pay
          </Button>

I have error

Error: Do not render the PayPal button into a button element

But I strictly want to use this button for calling paypal, is it possible to overcome this error but to still use this button for paying?

javascript – Removing video element not working with Reactjs

I’m creating a WebRTC app where I need to show the new users video feed when its connected and removing when they’ve left.

import React, { Component } from 'react';
import Peer from 'peerjs';


class Host extends Component {
    constructor(props) {
        super(props);
        this.peer = new Peer();
        this.state = { streams: () };
    }

    async componentDidMount() {
        const self = this;

        this.peer.on('open', function(id) {
            self.peer.on('call', (call) => {
                console.log('Incoming call...');
                call.answer(stream);
                call.on('stream', (remoteStream) => {
                    let streams = (...self.state.streams, {src: remoteStream, connId: call.connectionId, display: true});
                    self.setState({ streams });
                    console.log('Call received...');
                })

                call.on('iceStateChanged', (state) => {
                    if (state == 'disconnected') {
                        self.setState(prevState => ({
                        streams: prevState.streams.map(
                            s => s.connId === call.connectionId ? { ...s, display: false }: s
                        )}))
                        console.log('Call disconnected');
                    }
                })
            })
        }
    }
    
    render() {
        return(
            <>
            {this.state.streams.map((stream, idx) => {
                if (!stream.display)
                    return null

                return <video autoPlay key={idx} ref={(ref) => {ref.srcObject = stream.src}}></video>
            })}
            <>
        );
    }
}

export default Host;

I’m able to dynamically create the video element but removing is where I’m facing problems.
Whenever iceStateChanged event is called i.e. when user disconnects it throws the following error.

Uncaught TypeError: Cannot set property 'srcObject' of null

reactjs – Input value is rendered twice as one element when pushed into an array

When I type a word into the input and press the Append button, the word is then pushed into an array.

However, the word is rendering twice as one element in the array. “Foo” would be pushed into the array as [“Foo Foo”]

When Undo button is pressed, the element is popped. [“Foo Foo”] becomes [].

Please point me to the right direction.

react.js – React wrapper for existing library

https://github.com/BingXiong1995/react-flv-player/blob/master/lib/wrapper/ReactFlvPlayer.js

import React, { Component } from 'react';
import flvjs from './flv.min';
import PropTypes from 'prop-types';


class ReactFlvPlayer extends Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
    this.flvPlayerRef = element => {
      this.flvPlayerRef = element;
    };
  }

  componentDidMount() {

    const {type , url, isLive, enableStashBuffer, stashInitialSize, hasAudio, hasVideo, handleError, enableWarning, enableError} = this.props;

    // 组件挂载后,拿到Ref进行操作
    if (flvjs.isSupported()) {
      const flvPlayer = flvjs.createPlayer({
        type,
        isLive,
        url,
        hasAudio,
        hasVideo
      },{
        enableStashBuffer,
        stashInitialSize
      });


      flvjs.LoggingControl.enableError = false;
      flvjs.LoggingControl.enableWarn = enableWarning;

      flvPlayer.attachMediaElement(this.myRef.current); // 将这个DOM付给第三方库
      flvPlayer.load();
      flvPlayer.play();
      flvPlayer.on('error', (err)=>{
        // console.log(err);
        handleError(err);
      });
    }
  }

  render() {
    const { height, width, isMuted,showControls } = this.props;
    return (
      <div>
        <video
          controls={showControls}
          muted={{isMuted}}
          ref={this.myRef}
          style={{height, width}}
        />
      </div>
    );
  }
}

ReactFlvPlayer.propTypes = {
  type: PropTypes.string,
  url: PropTypes.string.isRequired,
  isLive: PropTypes.bool,
  showControls: PropTypes.bool,
  hasAudio: PropTypes.bool,
  hasVideo: PropTypes.bool,
  enableStashBuffer: PropTypes.bool,
  stashInitialSize: PropTypes.number,
  height: PropTypes.string,
  width: PropTypes.string,
  isMuted: PropTypes.bool,
  enableWarning: PropTypes.bool,
  enableError: PropTypes.bool,
  handleError: PropTypes.func
};

ReactFlvPlayer.defaultProps = {
  type: 'flv',
  isLive: true,
  hasAudio: true,
  hasVideo: true,
  showControls: true,
  enableStashBuffer: true,
  stashInitialSize: 128,
  height: '100%',
  width: '100%',
  isMuted: false,
  handleError: (err)=>{console.log(err)},
  enableWarning: false,
  enableError: false
};

export default ReactFlvPlayer;

Wrote some wrapper a long time ago. I am wondering if I could have done it in a better way. What are some of the improvements I could make or issues with the code. Thanks.

javascript – Problemas ao acrescentar script do Spotify com reactJS

Eu estava tentando linkar o script da API do spotify no componente do React, mas quando vou usar a função “window.onSpotifyWebPlaybackSDKReady” ele mostra o erro:”property onSpotifyWebPlaybackSDKReady does not exist on type ‘Window & typeOf globalThis”, como se não reconhecesse o script.Como posso resolver isso ?

import React, { useEffect, useState } from 'react';

function SpotifyPlayer() {

    useEffect(() => {
    const script = document.createElement("script");
    script.src = "https://sdk.scdn.co/spotify-player.js";
    script.async = true;
    document.body.appendChild(script);
    window.onSpotifyWebPlaybackSDKReady = () => {
      // do your spotify magic here.
    }
    }, ());
      
}

export default SpotifyPlayer;

OBS: o HTML principal está em uma pasta e o componente em outra, mas já tentei colocar o script tag no body do html principal e, ainda assim, ele não reconheceu a função no componente.

react – Manipulando retorno de função Async/Await com JSON.parse – REACTJS

O problema está acontecendo porque o tipo do seu ret.value é uma união entre string e null.

Mesmo que no seu teste ele seja uma string, a declaração desse tipo contempla a possibilidade dele ser null também, e o tipo null não é uma parâmetro válido para o método JSON.parse, portanto o compilador não está aceitando o mesmo.

Para passar o parâmetro para o método JSON.parse, você pode utilizar um dos muitos shields do TypeScript. Se você adicionar um if para se certificar que ret.value é do tipo string dentro de determinado escopo, isso já será o suficiente para o compilador se certificar que ele é válido:

async getObject() {
    const ret = await Storage.get({ key: 'user' });
    if (typeof ret.value === 'string') {
        // dentro desse escopo você pode utilizar ret.value como se ele sempre fosse uma string
        console.log(JSON.parse(ret.value));
    }
}

Outra abordagem que você pode utilizar é criar uma variável que é do tipo string, e exclusivamente string:

async getObject() {
    const ret = await Storage.get({ key: 'user' });
    const value = ret.value ?? '';
    console.log(JSON.parse(value));
}

No exemplo acima, se ret.value for null o operador coalesce (??) irá resultar na string vazia, portanto o tipo de value não tem como ser null, logo é um parâmetro válido para JSON.parse