StackUnderFlow
StackUnderFlow

Reputation: 367

How to query in firebase database in react?

I have the following data structure in firebase as a realtime database:

{
  "react" : {
    "url_01" : "https://stackoverflow.com/",
    "url_02" : "https://google.com/",
    "url_03" : "https://www.youtube.com/"
  }
}

I'm trying to query the database in React to display all URLs in the below component.

So far I got it to display the first URL in the database correctly but now trying to display them all in the div as <h1>.

class FirebaseDB extends React.Component {
  constructor() {
    super();
    this.state = {
      speed: [],
    };
  }

  componentDidMount() {
    const rootRef = firebase.database().ref().child('react');
    const speedRef = rootRef.child('url_01');
    speedRef.on('value', snap => {
      this.setState({
        speed: snap.val()
      });
    });
  }

  render() {
    return (

        <div>
          <h1>URL: {this.state.speed}</h1>
        </div>


    );
  }
}

Upvotes: 0

Views: 2349

Answers (2)

Marco Rojas
Marco Rojas

Reputation: 452

componentDidMount() {
    const rootRef = firebase.database().ref();
    const speedRef = rootRef.child('react');

    speedRef.once("value", snap => {
        // Handle state
        let speedsUrls = []
        snap.forEach(child => {
            speedsUrls.push(child.val())
        });
        this.setState({speed: speedsUrls})
    });
}

render() {
    const SpeedURLS = this.state.speed.map(url => <h1>URL: {url}</h1>);
    return (
        <div>
            {SpeedURLS}
        </div>
    );
}

Upvotes: 7

Spring Page
Spring Page

Reputation: 1

Another solution:

const object1 = {
    "url_01" : "https://stackoverflow.com/",
    "url_02" : "https://google.com/",
    "url_03" : "https://www.youtube.com/"
};

let a = Object.values(object1);

a is now

["https://stackoverflow.com/","https://google.com/","https://www.youtube.com/"]

Upvotes: 0

Related Questions