0

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>


    );
  }
}

2 Answers 2

7
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>
    );
}
Sign up to request clarification or add additional context in comments.

2 Comments

anyway to get the results to display in the div as an h1 class? Having issues rendering it to the page.
Look at the new edition, you just need to render() using the array of urls
0

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/"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.