Document.querySelector returns Undefined

Asked

Viewed 88 times

-1

I need to recover an input value from my login screen and move to my home screen.

I made a document.querySelector to access my input through ID and stored this value in a const chamanda empresa.

Inside my home I imported this constant and made a console.log to check if I was receiving the data, at the same time I inserted it inside my setState to get the position of the Array equal to the company number. But the value returns Undefined.

I also get a warning:

Warning: Failed prop type: You provided a value prop to a form field without an onChange Handler. This will render a read-only field. If the field should be mutable use defaultValue. Otherwise, either set onChange or readOnly.

How can I fix this?

Login screen:

    import React, { Component } from 'react'
    
    import {LoginService} from "../../services/LoginService"
    
    import './loginPage.css'
    
    //Recebe o número da empresa
    export const empresa =  parseInt(document.querySelector("#empresa").value)
    
    
    class Login extends Component   {
   
        
        
        fazerLogin  =   infosDoEvento   =>  {
            
            
    
            infosDoEvento.preventDefault();
              const dadosDeLogin    =   {
                    login:  this.refs.inputLogin.value,
                    senha:  this.refs.inputSenha.value,
    
            };
            console.log(dadosDeLogin)
            LoginService.logar(dadosDeLogin)
            .then(()    =>  {
                    this.props.history.push("/home");
            })
            .catch(err  =>  {
                    console.error(`[Erro    ${err.status}]`,    err.message);
            });
        }
    
        
        
       
        render() {
            return (
                
                    <div className="loginPage">
                        <div className="container">
                       
                                <h2 className="loginPage__title">Seja bem vindo!</h2>
                                <form className="loginPage__form" action="/" onSubmit={this.fazerLogin}>
                                    <div className="loginPage__inputWrap">
                                        <label className="loginPage__label" htmlFor="login">Login</label> 
                                        <input ref="inputLogin" className="loginPage__input" type="text" id="login" name="senha"/>
                                    </div>
                                    <div className="loginPage__inputWrap">
                                        <label className="loginPage__label" htmlFor="senha">Senha</label> 
                                        <input ref="inputSenha" className="loginPage__input" type="password" id="senha" name="senha"/>
                                    </div>
    
                                    <div>
                                        <label className="loginPage__label" htmlFor="login">Empresa</label> 
                                        <input ref="inputEmpresa" className="loginPage__input" type="text"  id="empresa" name="empresa" />
    
                                    </div>
                                    <br></br>
                                    <div className="loginPage__inputWrap">
    
    
                                        <button className="loginPage__btnLogin" type="submit">
                                            Logar
                                        </button>
                                    </div>
                                </form>
                       
                        </div>
                    </div>
             
            )
        }
    }
    
    export default Login;

Home screen:

 

    import React, { Component } from 'react'
    import { Container, Table} from 'react-bootstrap'
    import Extrato from '../Extrato'
    import NavBar from '../NavBar'
    
    import {consultarResumo} from '../../services/Home/index'
    
    //Importa o valor da Empresa
    import {empresa} from '../Login/index'
    
    //Imprime o valor da Empresa
    window.onload = teste => {console.log(empresa)}
    
    
    class Home  extends Component   {
        
        
    
        constructor(props){
            super(props);
    
            this.state = {
               
                empresaId: 0,
                    nomeEmpresa: "EMPRESA UM S/A",
                    cnpj: 0,
                
                dadosBancario: {
                    banco: 0,
                    bancoNome: "CONTA SIMPLES",
                    agencia: 0,
                    conta: 0,
                    digitoConta: 0
        },
                    saldo: 0
                
            }
            
        }
    
        componentDidMount(){
            
            //Consulta na API e busca a posição igual o valor da empresa
            consultarResumo().then(dados => this.setState(dados[empresa]))
            
        }
    
        render() {
            return (
            <Container>
            <NavBar></NavBar>   
               <br/>
                <Table striped bordered hover variant="dark">
                        <thead>
                            <tr>
                            <th>{this.state.nomeEmpresa}</th>
                            <th>CNPJ: {this.state.cnpj}</th>
                            <th>Número do Banco: {this.state.dadosBancario.banco}</th>
                            <th>{this.state.dadosBancario.bancoNome}</th>
                            <th>Agência: {this.state.dadosBancario.agencia}</th>
                            <th>Conta: {this.state.dadosBancario.conta}</th>
                            <th>Digito da Conta: {this.state.dadosBancario.digitoConta}</th>
                            <th>Saldo: {this.state.saldo.toLocaleString("PT-BR", {style: "currency", currency : "BRL"})}</th>
                            </tr>
                        </thead>
                    </Table>
                    <Extrato></Extrato>
            </Container>
            )
        }
        
    }
    
    export default Home;
    
  • 1

    All right here parseInt(document.querySelector("#empresa")).value? would not be parseInt(document.querySelector("#empresa").value)?

  • Even changing position, the problem persists.

  • Yes, it was just a detail that I called attention to solve. Now change onSubmit={this.fazerLogin} for onSubmit={(event) => this.fazerLogin(event)} and see if the Warning still appears

  • Warning continues, but now we have another error: Cannot read Property 'value' of null at Module.. /src/View/Login/index.js and the variable appears as Undefined in the console on the home screen.

  • Okay, I’ll write my answer with the tests I did here and we’ll see if it solves your problem

1 answer

2


Doing the tests here, I think I can solve your problem. Let’s go by part...

  • First, the inputs React has a different behavior than traditional, such as react documentation explains:

In HTML, form elements like , and usually maintain their own state and update it based on user input. In React, the changeable state is usually kept in the state property of the components and updated only with setState().

  • Soon, we will redo your component code Login, and we will create a state to maintain the states of inputs that will be changed as the user interacts. Recalling that the this.refs is depreciated, then we won’t use it. I hope it’s okay. I’ll comment on the code with explanations. We’ll add methods to treat the inputs
 // vamos adicionar um estado para manter os dados dos inputs.
  state = {
    login: '',
    senha: '',
    empresa: ''
  };

  // agora vamos adicionar metodos para tratar toda vez que um input mudar
  // depois vamos adicionar atributo `onChange` para cada input o metodo
  // equivalente
  inputLoginChangeHandler = event => {
    this.setState({ login: event.target.value });
  };
  inputSenhaChangeHandler = event => {
    this.setState({ senha: event.target.value });
  };
  inputEmpresaChangeHandler = event => {
    this.setState({ empresa: event.target.value });
  };

  fazerLogin = infosDoEvento => {
    infosDoEvento.preventDefault();
    const dadosDeLogin = {
      login: this.state.login,
      senha: this.state.senha,
      empresa: this.state.empresa
    };
    console.log(dadosDeLogin);
    // ...
  };

On the form, we inputs let’s add attributes value and onChange:

render() {
    return (

      <div className="loginPage">
        <div className="container">

          <h2 className="loginPage__title">Seja bem vindo!</h2>
          <form className="loginPage__form" action="/" onSubmit={this.fazerLogin}>
            <div className="loginPage__inputWrap">
              <label className="loginPage__label" htmlFor="login">Login</label>
              <input ref="inputLogin" className="loginPage__input" type="text" id="login" name="senha" value={this.state.login} onChange={(event) => this.inputLoginChangeHandler(event)}/>
            </div>
            <div className="loginPage__inputWrap">
              <label className="loginPage__label" htmlFor="senha">Senha</label>
              <input ref="inputSenha" className="loginPage__input" type="password" id="senha" name="senha" value={this.state.senha} onChange={(event) => this.inputSenhaChangeHandler(event)}/>
            </div>

            <div>
              <label className="loginPage__label" htmlFor="login">Empresa</label>
              <input ref="inputEmpresa" className="loginPage__input" type="text" id="empresa" name="empresa" value={this.state.empresa} onChange={(event) => this.inputEmpresaChangeHandler(event)}/>

            </div>
            <br></br>
            <div className="loginPage__inputWrap">


              <button className="loginPage__btnLogin" type="submit">
                Logar
                                    </button>
            </div>
          </form>

        </div>
      </div>

    );
  • In the tests I did, that was enough to solve the Warning. Try to do the tests. Remember I didn’t put all your code, but I think you can adapt.
  • Now, let’s solve the problem of empresa was undefined. Here’s what happens when you try to capture parseInt(document.querySelector("#empresa").value) before React renders the Login component, the HTML input component with the id company does not exist yet, so there is no way to have the value of this input, always will be null.
  • If Voce needs value empresa on another page, DO NOT USE EXPORTS. I suggest you use a state manager like Redux, transfer values from child component to parent component(see here),or even use the localStorage(see here), where you can store the value of enterprise and use on another page. For example, in the function fazerLogin, save the value of enterprise in the localStorage:
 fazerLogin = infosDoEvento => {
    infosDoEvento.preventDefault();

    const dadosDeLogin = {
      login: this.state.login,
      senha: this.state.senha,
      empresa: this.state.empresa
    };
    
    window.localStorage.setItem('empresa', dadosDeLogin.empresa);
    // ...
  };

And where you need the value of empresa use for example:

let empresa = window.localStorage.getItem('empresa');

I hope my answer may have helped you.

  • It worked perfectly! Your help was amazing! In addition to solving the problem gave me a lesson and helped me understand many things and improve my way of programming.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.