4est
4est

Reputation: 3168

Get Data from Firebase (React, Axios)

I got firebaseConfig.js

import firebase from 'firebase/app'
import 'firebase/firestore'

const firebaseConfig = {
    apiKey: "somekey",
    authDomain: "somekey",
    databaseURL: somekey",
    projectId: "somekey",
    storageBucket: "somekey",
    messagingSenderId: "somekey",
    appId: "appIdKey"
  };

  firebase.initializeApp(firebaseConfig)    
  const db = firebase.firestore()    
  const TestRef = db.collection('myDB')

  export {TestRef}

Now I got Component index.js

import {ToDosRef} from './firebase'
import axios from 'axios';

const useAPI = endpoint => {
  const [data, setData] = useState([])

  useEffect(() => {
    getData();
  },[])

  const getData = async() => {
  
    const response = await axios.get(endpoint)
    
    console.log(response.data())

    setData(response.data)
  }

  return data
}

const App = () => {
  ....
  const savedTodos = useAPI(ToDosRef)
  
  return(
    <div>
    </div>
  )
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
)

I think something I did wrong with axios.get(endpoint) as I'm getting 'Request failed with status code 404'

Upvotes: 1

Views: 3193

Answers (2)

4est
4est

Reputation: 3168

I found some blog and did as below and is working now:

To firebaseConfig.js I have added:

const ToDosRef = axios.create({baseURL: 'https://firestore.googleapis.com/v1/projects/project_id/databases/(default)/documents'})    
export {ToDosRef} 

Then index.js:

  const getData = async() => {

    const fbData = await endpoint.get(`/mDocumentName`)
    .then(response => { 
         console.log(response.data);
         console.log(response.data.documents);

        response.data.documents.forEach(x => {
          console.log(x);
          console.log(x.fields.id);
        })

       })
       .catch(error => { 
           console.log(error); 
       });
  }

Upvotes: 1

Nooruddin Lakhani
Nooruddin Lakhani

Reputation: 6967

Your endpoint url should be something like

axios.get('/user?ID=12345').then(function (response) { 
  console.log(response); 
}) .catch(function (error) { 
  console.log(error); 
});

Upvotes: 1

Related Questions