Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

170
Vistas
react prevent children render ( ajax loader waiting for response )

Im trying to write simple ajax loader and I wondering that i can prevent props.children render in parent container. The problem is that children want to render, no matter that Loader want to show it or not, and if render is based on ajax data that cousing errors.

Example: https://jsfiddle.net/j8dvsq39/

Example2: This example will produce error couse this.state.data.user is undefined before ajax request.

Loader:

import React from 'react'
export default React.createClass({

    getDefaultProps() {
        return { text: "Loading", loaded: false };
    },

    render() {

        if(this.props.loaded == false)
            return <div>{this.props.text}</div>;
        else
            return <div>{this.props.children}</div>;
    }
})

Class using Loader

import React from 'react'
import Loader from '../helpers/Loader';
import {comm} from '../Comm';

export default React.createClass({

    getInitialState() {
        return {loaded: false, data: null};
    },
    componentWillMount(){
        comm.get("/xxx/xxx", {json: 1}, (back) => {
            console.log(back);
            this.setState({loaded: true, data: back});
        });
    },
    render(){
        return <Loader loaded={this.state.loaded}>{this.state.data.user.name}</Loader>
});
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Reason is, initially you defined data=null and before the ajax call you are using this.state.data.user.name, it will throw the error:

Cannot read property 'name' of undefined

Simple solution is you need to put the check on data until you didn't get the ajax response, Check this:

var Loader = React.createClass({
    getDefaultProps() {
        return { text: "Loading", loaded: false };
    },
    render() {
        if(this.props.loaded == false)
            return <div>{this.props.text}</div>;
        else
            return <div>{this.props.children}</div>;
    }
});

var Hello = React.createClass({
    getInitialState() {
        return {loaded: false, data: null};
    },
   componentWillMount(){
       setTimeout(()=>{
            this.setState({loaded: true, data: {user:{name: "login"}}});
        }, 1000);
    },

  render: function() {
  var user = null;  
    return <Loader loaded={this.state.loaded}>
              <div>
                 Hello {this.state.data ? this.state.data.user.name : null}
              </div>
           </Loader>;
  }
});

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='container'/>

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda