React: How can I send data to this.state

Asked

Viewed 24 times

-1

Good evening, I’m starting in React and have the following line:

class Namelist extends React.Component{ constructor(props){ super(props); firebase.initializeApp(config);

    this.state = {
        clientes: []
    };
}

componentDidMount(){
    this.getUserData();
}


getUserData = () => {
    let ref = firebase.database().ref('/');
    ref.on('value', snapshot => {
        const state = snapshot.val();
        this.setState(state);
        console.log(state);
    });
    console.log("Dados Recebidos !")
};

render() {
    const { clientes } = this.state;
    return(
        <IonList>
        {clientes.map((item,index) => 
        <IonItem key={index}> 
        <IonLabel>
        <p>Nome:</p>
        <h2>{item.Name}</h2>
        <p>Horário:</p>
        <h2>{item.Horario}</h2>
        </IonLabel>
        <IonLabel></IonLabel>
        <IonLabel>
        <IonButton color="success"><IonIcon icon={checkmark} /></IonButton>
        <IonButton color="danger"><IonIcon icon={trash} /></IonButton>
        </IonLabel>
        </IonItem>
        )}
    </IonList>

    );
} 

}

What I’m not getting is just filling in the state which has the array of clients, to redenrize a list. It’s all functional, the data is coming however the {clients} = this.state is not filled with them.

  • What you have in your snapshot.val()?

  • comes the data from firebase, exactly like this: customers: [{name: 'Test', schedule: 'test'}]

  • If you use another variable name to store this, does it work? (ex: const newState = await ... and then this.setState(newState)) Because if the value is really right, I don’t see any problems beyond you creating a variable with the same name as state.

  • I’ll try here, I’ll get back to you soon, but thanks anyway !

1 answer

0

Try to use it this way:

getUserData = () => {
    let ref = firebase.database().ref('/');
    ref.on('value', snapshot => {
        const {clientes} = snapshot.val();
        this.setState({clientes: clientes}); // ou this.setState({clientes})
        console.log(clientes);
    });
    console.log("Dados Recebidos !")
};

Note if the console.log(clientes) returns : [{nome: 'Teste', horario: 'teste'}] , if not, its function getUserData is not receiving data correctly.

Browser other questions tagged

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