Ste Fandy
Ste Fandy

Reputation: 69

React fetch Firebase get unique key value

does anyone know how to get unique key value from firebase database? i want to store it inside state and print it into console.log.

this is example of unique key enter image description here

this is the code, i just want to show it in console

import React, { Component } from "react";

export class Test extends Component {
  constructor(props) {
    super(props);

    this.state = {
      newId: ""
    };
  }

  componentDidMount() {
    fetch("https://redditclone-project.firebaseio.com/data.json", {
      method: "get",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json"
      }
    })
      .then(res => res.json())
      .then(res => {
        console.log(res);
      });
    console.log('value key, ex:-LzpvyLJnKgDllnTE-eW');
  }
  render() {
    return <div></div>;
  }
}

export default Test;

enter image description here

thanks

edit : inside res and added my firebase link

Upvotes: 0

Views: 681

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598775

If you only want to print the keys from the JSON, you can use Object.keys():

.then(res => res.json())
.then(res => {
  console.log(Object.keys(res));
});

Since Object.keys() returns an array, you can then also use for example Array.forEach() to loop over these keys.

Upvotes: 1

Related Questions