How can I fix error when trying to render data? - reactjs

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.

Related

fetching data not showing in table in react

I am create a table and fetching data using axios but in the table I am not able to print the data when I check data is printing in browser but not able to print the particular data to a table format so what should be change in my code?
import { useEffect, useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { Table } from "react-bootstrap";
import axios from "axios";
export default function App() {
const [user, setUser] = useState([]);
useEffect(() => {
axios
.get("https://jsonplaceholder.typicode.com/users", (req, res) => {
res.json();
})
.then((data) => setUser({ ...user, data }))
.catch((error) => console.error(error));
});
return (
<div className="App">
<h3 className="text-primary">User List</h3>
<Table
variant="danger"
striped
bordered
hover
className="shadow-lg text-center"
>
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>UserName</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{user?.data?.length > 0 &&
user.data.map((user) => {
return (
<tr key={user.id}>
<td>{JSON.stringify(user.data["data"].id)}</td>
<td>{JSON.stringify(user.data["data"].name)}</td>
<td>{JSON.stringify(user.data["data"].username)}</td>
<td>{JSON.stringify(user.data["data"].email)}</td>
</tr>
);
})}
</tbody>
</Table>
{/* <div>{JSON.stringify(user.data["data"])}</div> */}
</div>
);
}
for example
import { useEffect, useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { Table } from "react-bootstrap";
import axios from "axios";
export default function App() {
const [user, setUser] = useState([]);
useEffect(() => {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then((res) => {
setUser(res.data);
})
.catch((error) => console.error(error));
}, []);
return (
<div className="App">
<h3 className="text-primary">User List</h3>
<Table
variant="danger"
striped
bordered
hover
className="shadow-lg text-center"
>
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>UserName</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{user?.length > 0 &&
user.map((userData) => {
return (
<tr key={userData.id}>
<td>{userData.id}</td>
<td>{userData.name}</td>
<td>{userData.username}</td>
<td>{userData.email}</td>
</tr>
);
})}
</tbody>
</Table>
{/* <div>{JSON.stringify(user)}</div> */}
</div>
);
}
Replace the useEffect code as follow.
useEffect(() => {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then((data) => setUser({ ...user, data }))
.catch((error) => console.error(error));
}, []);
You already know that calling this api will give you an array of users so you can initialise the state as empty array as:
const [users, setUsers] = useState([]);
and when you are using axios then you don't have to use res.json(). axios will do it for you out of the box.
axios
.get("https://jsonplaceholder.typicode.com/users")
.then(({ data }) => setUsers(data))
.catch((error) => console.error(error));
so, after getting data using get method of axios it will return you a promise and you can get data from its data property that is passed an first args. You can directly set state which will be an array of objects.
.then(({ data }) => setUsers(data))
Here I've destructed the object to get only the data property.
Since users will be an array of objects, so you don't have to do any check. You can directly use user.id to get the respective property.
Codesandbox link
export default function App() {
const [users, setUsers] = useState([]);
useEffect(() => {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then(({ data }) => setUsers(data))
.catch((error) => console.error(error));
}, []);
return (
<div className="App">
<h3 className="text-primary">User List</h3>
<Table
variant="danger"
striped
bordered
hover
className="shadow-lg text-center"
>
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>UserName</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{users.map((user) => {
return (
<tr key={user.id}>
<td>{user.id}</td>
<td>{user.name}</td>
<td>{user.username}</td>
<td>{user.email}</td>
</tr>
);
})}
</tbody>
</Table>
{/* <div>{JSON.stringify(user.data["data"])}</div> */}
</div>
);
}

Placing Fetch Data to React Table

I am trying to get API fetch data from my server and database to a React table. Everything seems to load and fetch the data and network seem to come in my network, but the data is still not presented in it and turns up plank with the table header.
For the data I am passing, this is a nested object file.
For example,
{
_id: Number...,
national_id: 0,
name: 'Test School',
coach: Head Coach
{
Here is table.js:
import React from 'react';
const DisplayTable = ({data}) => {
return (
<div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Coach</th>
</tr>
</thead>
<tbody>
{Object.keys(data).map(item => (
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.coach}</td>
</tr>
))}
</tbody>`
</table>
</div>
)
} export default DisplayTable
Here is my file where I intend to fetch and use that fetched data to be arranged with my displayTable
import React, { useEffect, useState } from "react";
import Table from '../TableMentor/table';
function FilterTable() {
const [elements, setElements] = useState([])
useEffect(() => {
var postData = ['national_id:', 'name', 'coach']
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(postData)
};
fetch('/api/get-data', requestOptions).then(res => res.json()).then(
data => {
setElements(data.collection)
})
},[]);
return (
<div className="app">
<h1> React Table </h1>
<Table data={elements} />
</div>
);
}
export default FilterTable;
Here is an image:
The Resulted Page

unable to fetch firebase realtime database data into website UI using 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.

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>
);
}

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