unable to fetch firebase realtime database data into website UI using ReactJs - reactjs

I am new to firebase (version-9) , and after trying alot , i am unable to fetch the data from firebase realtime database , i can see the data in console , but i want to render it into my website table, please help. below is my code snippet .
``
import React, {useState, useEffect} from 'react';
import { db } from '../firebase-config';
import { Link } from 'react-router-dom';
import { ref, onValue } from 'firebase/database';
const ViewAll = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
const posts = ref(db, 'superadmin/admins/')
onValue(posts,(snapshot) => {
const json = ({...snapshot.toJSON()})
const keys = Object.keys(json);
const postJSON = keys.map(key => {
const element = json[key];
return [element.FullName,element.doctors, element.technicians, element.patients]
});
setPosts(postJSON);
console.log({...snapshot.val()})
})
}, []);
``
``
return (
<div style={{marginTop: "100px"}}>
<table className='styled-table'>
<thead>
<tr>
<th style={{textAlign: "center"}}>No.</th>
<th style={{textAlign: "center"}}>Name</th>
<th style={{textAlign: "center"}}>Action</th>
</tr>
</thead>
<tbody>
{Object.keys(posts).map((id,index)=>{
return (
<tr key={id}>
<th scope='row'>{index + 1}</th>
<td>{posts[id].name}</td>
<td>
<Link to={'/SuperAdmin/ViewAll'}>
<button className='btn btn-view'>View</button>
</Link>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)
}
export default ViewAll
``
This is my code snippet
code snippet part 2
I'm Using Firebase version 9 in reactjs.
I am able to view the data in the console , I just want to render it into my website , and since i am new to firebase , i dont know how to render it in the website,
any sort of help will be hihgly appreciated.

Related

Extract a phpmyadmin table name using react

ello,
I created a CRUD application based on mysql database and react as framework,
As i’m going to use multiple tables in the database, I want to create a first page that extracts from the database all the tables names on a list. Once the list with the tables names is created, i want to be able to click on the table name and be redirected to the CRUD page that I already created.
The code below is what I used to create the first page but it failed to work.
I attached phpmyadmin database and the capture of structure of the project
import React, { useState, useEffect } from "react";
import axios from "axios";
const TabList = () => {
const [tab, settab] = useState("");
useEffect(() => {
axios.get('http://localhost/phpmyadmin/index.php?
route=/database/structure&server=1&db=crud_db')
.then(res=>{
console.log(res)
settab(res.data)
})
.catch(err=>{
console.log(err)
})
}, []);
return (
<div className="columns mt-5 is-centered">
<div className="column is-half">
<table className="table is-striped is-fullwidth">
<thead>
<tr>
<th>N</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{tab.map((tab , index) => (
<tr key={tab.id}>
<td>{index + 1}</td>
<td>{tab.name}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
};
export default TabList;
tables
vsc
vsc

How can I fix error when trying to render data?

I'm making an application to render the data in a table dynamically. But this error appears: "getUserData.map is not a function".
I didn't find any apparent errors, how can I solve this problem?
API: link
console: console
useRequestData:
import axios from "axios"
import { useEffect, useState } from "react"
export const useRequestData = (initialState, url) => {
const [data, setData] = useState(initialState)
useEffect(() => {
axios.get(url)
.then((res) => {
setData(res.data)
})
.catch(() => {
alert('Erro')
})
}, [url])
return data
}
Component:
import { Container, TableHeader } from "./styles"
import plusImg from "../../assets/plus.png"
import minusImg from "../../assets/minus.png"
import editImg from "../../assets/edit.png"
import { useRequestData } from "../hooks/useRequestData"
import { baseUrl } from "../../services/api"
export const UsersTable = () => {
const getUserData = useRequestData([], baseUrl)
return (
<Container>
<table>
<thead>
<tr>
<th>
<img src={plusImg} alt="" />
</th>
<th>Nome</th>
<th>Endereço</th>
<th>Cidade</th>
<th>UF</th>
<th>Telefone</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
{getUserData.map((user) => (
<tr key={user.TECL_ID}>
<tr>
<td>
<img src={minusImg} alt="" />
</td>
<td>
<img src={editImg} alt="" />
</td>
</tr>
<td>{user.TECL_NOME}</td>
<td>{user.TECL_ENDERECO}</td>
<td>{user.TECL_CIDADE}</td>
<td>{user.TECL_UF}</td>
<td>{user.TECL_TELEFONE}</td>
<td>fulano#gmail.com</td>
</tr>
))}
</tbody>
</table>
</Container>
)
}
Few things, inside your custom hook, create a function to get the data outside of the useEffect and THEN, run it inside useEffect.
Now, you have to return your data state from your custom hook in order to use it, so... At the bottom of your custom hook (outside of useEffect) write this:
return { data };
Now in your Component you could do something like this:
const { data } = useRequestData([], baseUrl)
And that's pretty much it, let me know if that helps.

How can i change this code to react redux

Here i want to change this code to react redux. How i can change this code using react redux. Kindly provide any solutions for changing this code to react redux using GET method api. As iam new to react js how can i change this code using react redux.
import React from "react";
import { useState, useEffect } from "react";
import { Link } from "react-router-dom";
export default function User() {
const [users, setUsers] = useState([]);
const f = async () => {
const res = await fetch("https://reqres.in/api/userspage=1");
const json = await res.json();
setUsers(json.data);
};
useEffect(() => {
f();
}, []);
const handleLogout = (e) => {
localStorage.clear();
window.location.pathname = "/";
}
return (
<div>
<h1>List Users</h1>
<div>
<button onClick={handleLogout}>Logout</button>
<nav>
<Link to="/Home">Home</Link>
</nav>
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>First_name</th>
<th>Last_name</th>
<th>Email</th>
<th>Avatar</th>
</tr>
</thead>
<tbody>
{users.length &&
users.map((user) => {
return (
<tr>
<td> {user.id}</td>
<td>{user.first_name}</td>
<td> {user.last_name} </td>
<td>{user.email}</td>
<td> <img key={user.avatar} src={user.avatar} alt="avatar" /></td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
);
}

Can someone explain in detail or provide a video link that can help me understand how to sort a mongodb in react

I saw different versions but honestly they make no sense. I tried to implement them so I can understand it myself but I didn't know where I should put it at. does it go in my view main.js file or what file and then where in that file does it go.
import React, { useState, useEffect } from 'react'
import axios from 'axios'
import { Link } from '#reach/router'
const Main = props => {
const [pets, setPet] = useState()
useEffect((req, res) => {
axios.get(`http://localhost:8000/api/users`)
.then(res => {// does the sort go here
// console.log(res.data.users)
setPet(res.data.users)
})
}, [])
// would the sort go before or in here ?
return (
<div>
These pets need a home: do you know any other pets Add Pet
<table className='table table-striped table-dark '>
<thead className="">
<tr>
<th>Name</th>
<th>Type</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{
pets ?
pets.map((pet, i) => {
return (
<tr key={i}>
<td>{pet.pet_name}</td>
<td>{pet.pet_type}</td>
<td><Link to={`/viewpet/${pet._id}`}>Detail</Link> | <Link to={`/update/${pet._id}`}>Edit</Link></td>
</tr>
)
})
: ''
}
</tbody>
</table>
</div>
)
}
export default Main;
Thanks to #hellogoodnight and some help to other folks to help me understand what you were saying.
the answer was what you said :)
setPet(res.data.users.sort((a, b) => a.pet_name < b.pet_name ? -1 : 1)

Why is my data not displaying in the table in react

Does anyone know why my data isn't displaying, it console.logs 'x[0]', 'x[1]', 'x[2]', and 'x[3]' fine in my return statement. I'm pretty new to react and programming in general so I have no idea why this doesn't work.
I would just expect it to fill the rows of the table like the 2 I've manually coded in.
import React, { useState, useEffect } from 'react'
import "./stylesheets/oddsmatcher-table.css"
const App = () => {
const [wow, setWow] = useState([])
useEffect(() => {
fetch(DATA)
.then(res => res.json())
.then(data => {
const newData = data.data.slice(0, 10)
const k = newData.map(x => {
return [x.date, x.event_name, x.bookmaker_name, x.exchange]
})
setWow(k)
console.log(k)
})
}, [])
return(
<table>
<tbody>
<tr>
<th>Date</th>
<th>Event</th>
<th>Bookie</th>
<th>Exchange</th>
</tr>
<tr>
<td>25-09-2020</td>
<td>Man United vs Liverpool</td>
<td>Bet365</td>
<td>Smarkets</td>
</tr>
<tr>
<td>26-09-2020</td>
<td>Arsenal vs Man City</td>
<td>Coral</td>
<td>Betfair Exchange</td>
</tr>
{wow.forEach(x => {
return(
<tr>
<td>{x[0]}</td>
<td>{x[1]}</td>
<td>{x[2]}</td>
<td>{x[3]}</td>
</tr>
)
})}
</tbody>
</table>
)
}
export default App
Update: Try switching your wow.forEach to this:
{wow.map((x, index) => {
return (
<tr key={index}>
{x.map((dataPiece) => (
<td key={dataPiece}>{dataPiece}</td>
))}
</tr>
);
})}
Here's the Codesandbox I was using to test. I replaced your async fetch with a global variable with what I think your wow data looks like:
https://codesandbox.io/s/suspicious-glitter-mf0tg?fontsize=14&hidenavigation=1&theme=dark
Let me know if that works. If it doesn't, can you post an example of what your fetched data looks like?

Resources