Not able to show fetched data from firebase into reactjs webapp - javascript

import React, { Component } from 'react'
import * as ReactBootStrap from 'react-bootstrap'
import { Table } from 'react-bootstrap'
import firebase from '../fire'
import '../App.css'
import Foot from './Foot'
class Appointment extends Component {
state = {
data: []
}
componentDidMount() {
firebase.database().ref("appoinment").once("value").then(snapShot => {
snapShot.forEach(item => {
this.state.data.push({
id: item.key,
name: item.val().name,
age: item.val().age,
gender: item.val().gender,
Description: item.val().Description,
date: item.val().Appointdate
});
})
})
}
render() {
return (
<div className='cardback'>
<div>
<br></br>
{console.log(this.state)}
<br></br>
<h2 style={{ textAlign: 'center', fontSize: '30px' }}>Today's Appointment</h2>
<br></br>
<br></br>
<Table striped bordered hover variant="dark" style={{ width: "1200px", margin: 'auto' }}>
<thead>
<tr>
<td>id</td>
<td>name</td>
<td>age</td>
<td>gender</td>
<td>Description</td>
<td>date</td>
<td>Status</td>
</tr>
</thead>
<tbody>
**{
this.state.data.map((item) =>
<tr>
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.age}</td>
<td>{item.gender}</td>
<td>{item.Description}</td>
<td></td>
</tr>
)
}**
</tbody>
</Table>
<br></br>
<br></br>
</div>
<Foot></Foot>
</div>
)
}
}
export default Appointment;
This is above is code
I want to fetch data from the firebase to react-js application. I am able to get whole data at the console but not able to iterate it into table form. The is as below. In which I fetch data from firebase and pushed into an array data. So basically data is an array of objects. But I am not able to iterate i

You are mutating the state directly which will not cause any re-render. Don't do this.state.data.push({id:item.key,
Use this.setState
componentDidMount() {
firebase
.database()
.ref("appoinment")
.once("value")
.then((snapShot) => {
let updatedData = [];
snapShot.forEach((item) => {
updatedData.push({
id: item.key,
name: item.val().name,
age: item.val().age,
gender: item.val().gender,
Description: item.val().Description,
date: item.val().Appointdate,
});
});
this.setState({ data: updatedData });
});
}

Related

TypeScript: Property 'data' does not exist on type '{ children?: ReactNode; }'. ts(2339)

Question
I'm working on a small project with BlitzJS. I'm fetching some data but I keep getting this Typescript issue:
Property 'data' does not exist on type '{ children?: ReactNode; }'.ts(2339)
import { BlitzPage } from "blitz"
import Layout from "app/core/layouts/Layout"
export async function getServerSideProps() {
const response = await fetch(
"https://api.coingecko.com/api/v3/coins/markets?vs_currency=eur&order=market_cap_desc&per_page=10&page=1&sparkline=false"
)
const data = await response.json()
return {
props: {
data,
},
}
}
const MarketPage: BlitzPage = ({ data }) => { /////////// ERROR IS ON THIS LINE
console.log(data)
return (
<div>
<h1>This is Market Page</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Current Price</th>
</tr>
</thead>
<tbody>
{data.map((coin) => (
<tr key={coin.id}>
<td>
<p>{coin.name}</p>
</td>
<td>
<p>{coin.current_price}</p>
</td>
</tr>
))}
</tbody>
</table>
</div>
)
}
MarketPage.suppressFirstRenderFlicker = true
MarketPage.getLayout = (page) => <Layout>{page}</Layout>
export default MarketPage
I guess it's something with Typescript types but I don't work with Typescript so much. I'm having hard time finding solution.
Please can you help me with some guidance here.
Thanks!
Solution
Thanks to Ajay, I resolved the issue!
Here's working example:
import { BlitzPage } from "blitz"
import Layout from "app/core/layouts/Layout"
import { Table, Th, Td } from "app/core/components/Table"
interface CoinType {
id: string
name: string
current_price: string
}
interface PropType {
data: CoinType[]
}
export async function getServerSideProps() {
const response = await fetch(
"https://api.coingecko.com/api/v3/coins/markets?vs_currency=eur&order=market_cap_desc&per_page=10&page=1&sparkline=false"
)
const data = await response.json()
return {
props: {
data,
},
}
}
const MarketPage: BlitzPage<PropType> = ({ data }) => {
return (
<div>
<h1>This is Market Page</h1>
<Table>
<thead>
<tr>
<Th>Name</Th>
<Th hasNumber>Current Price</Th>
</tr>
</thead>
<tbody>
{data.map((coin) => (
<tr key={coin.id}>
<Td>
<p>{coin.name}</p>
</Td>
<Td hasNumber>
<p>{coin.current_price}</p>
</Td>
</tr>
))}
</tbody>
</Table>
</div>
)
}
MarketPage.suppressFirstRenderFlicker = true
MarketPage.getLayout = (page) => <Layout>{page}</Layout>
export default MarketPage
Typescript is showing errors because, You had not explain any type. You can create your type with
interface CoinType {
id: string;
name: string;
current_price: string;
}
interface PropType {
data: CoinType[];
}
Once You have created Types, then
const MarketPage: BlitzPage = ({ data }:PropType) => {
console.log(data)
return (
<div>
<h1>This is Market Page</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Current Price</th>
</tr>
</thead>
<tbody>
{data.map((coin) => (
<tr key={coin.id}>
<td>
<p>{coin.name}</p>
</td>
<td>
<p>{coin.current_price}</p>
</td>
</tr>
))}
</tbody>
</table>
</div>
)
}
I hope It would work correctly :-)

Rendering React Table [v7] results in [object Object]

I'm new to Javascript so please bear with me. I'm attempting to render a table of data inside a div and I'm unable to do so. Basically I just want to replace the div in the html with the table div we've created.
I'm using react table v7 with webpack. The following code results in this being seen in the browser where the table should be.
Here is my code:
import { useTable } from 'react-table';
const ReactTable = require('react-table');
import React from 'react';
const tableData = [
{someColumn: 1, someOtherColumn: 'A'},
{someColumn: 2, someOtherColumn: 'B'}
]
const columnGenerator = (columnNames) => {
var updatedNames = columnNames.map(c => {
return {
Header: camelToTitle(c),
accessor: c
}
});
return [
{
Header: "Claims Data",
columns: updatedNames
},
]
};
const Table = ({ columns, data }) => {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow
} = useTable({
columns,
data
});
return (
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>{column.render("Header")}</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map((row, i) => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
})}
</tr>
);
})}
</tbody>
</table>
);
};
const table = <div>
<Table
columns={columnGenerator(Object.keys(tableData[0]))}
data={tableData}
/>
</div>
document.getElementById('claim-table').append(table);
[object Object] is just what is being rendered by converting that table object into a String. I would start by trying to use ReactDOM to mount that node instead of append:
import ReactDOM from 'react-dom'
...
ReactDOM.render(<Table
columns={columnGenerator(Object.keys(tableData[0]))}
data={tableData}
/>,
document.getElementById('claim-table')
)

how to hide table rows based on an input in react js

i created an app using react js which get te data from a graphql endpoint .
the data is displayed in a table and i ant to add a search function .
when the attribute name match the input in the search field only the roes that contains that name will stay displayed so basically i ant to hide the other rows
search component :
import React, { useState } from 'react'
const Search = ({ getQuery }) => {
const [text, setText] = useState('')
const onChange = (q) => {
setText(q)
getQuery(q)
}
return (
<section className='search'>
<form>
<input
type='text'
className='form-control'
placeholder='Search characters'
value={text}
onChange={(e) => onChange(e.target.value)}
autoFocus
/>
</form>
</section>
)
}
export default Search
orders list :
import React , { useState, useEffect } from 'react'
import { gql, useQuery } from '#apollo/client';
import Table from 'react-bootstrap/Table'
import Moment from 'react-moment';
import moment from "moment";
import { Link } from 'react-router-dom';
import Row from 'react-bootstrap/Row'
import Col from 'react-bootstrap/Col'
import { DangerousChangeType } from 'graphql';
import Search from './Search'
import Button from 'react-bootstrap/Button'
const GET_All_Orders = gql`
query Orders($input1: PaginationInput) {
Orders(input: $input1){
pageInfo {
hasNextPage
hasPreviousPage
}
edges{
cursor
node {
id
closed
email
createdAt
updatedAt
cancelledAt
displayFinancialStatus
displayFulfillmentStatus
lineItems{
edges{
node {
customAttributes{
key
value
}
id
quantity
title
variant{
id
image {
altText
id
src
}
title
weight
weightUnit
price
}
}
}
}
shippingAddress {
name
}
phone
subtotalPrice
totalPrice
totalRefunded
totalTax
processedAt
}
}
}
}
`;
export default function AllOrders({ input1 }) {
const { loading, error, data , fetchMore} = useQuery(GET_All_Orders, {
variables: {"input1": {
"num": 20,
}}
,
});
let date = new Date()
const [query, setQuery] = useState('')
if (loading) return <h4>読み込み中...</h4>;
if (error) return `Error! ${error}`;
return( <div>
<Row >
<Col xs={10}> <h5>すべての注文</h5></Col>
<Col><h5> 日付 : <Moment format="YYYY/MM/DD">
{ date}
</Moment> </h5></Col>
</Row>
<br/>
<Table responsive hover size="sm">
<thead>
<tr>
<th className="allOrders">注文日</th>
<th className="allOrders">名前</th>
<th className="allOrders">注文者メールアドレス</th>
<th className="allOrders" >配送状態</th>
<th className="allOrders" >支払状況</th>
<th className="allOrders" >合計金額</th>
<th className="allOrders" >詳細</th>
</tr>
</thead>
<tbody>
{data.Orders.edges.map(({ edges ,node :{id , createdAt , displayFulfillmentStatus , displayFinancialStatus , totalPrice , email , shippingAddress: {
name
} }}) => (
<tr key={id}>
<td> <Moment format="YYYY/MM/DD">
{createdAt}
</Moment></td>
<td>{ name} </td>
<td>{ email} </td>
{displayFulfillmentStatus == "FULFILLED" ? <td className="success">配送済み</td> : <td className="failed">未配送</td>}
{displayFinancialStatus == "PAID" ? <td>支払済み</td> : <td>未払い</td> }
<td>{totalPrice} </td>
<td>
<Link to={`/orders/${id}`} className="btn btn-light">
詳細
</Link></td>
</tr>
))}
</tbody>
</Table>
<div className="text-center">
<Button
variant="light"
onClick={() => {
fetchMore({
variables: {"input1": {
"num": 20,
"cursor": data.Orders.edges[data.Orders.edges.length - 1].cursor }},
updateQuery: (prevResult, { fetchMoreResult }) => {
fetchMoreResult.Orders.edges = [
...prevResult.Orders.edges,
...fetchMoreResult.Orders.edges
];
return fetchMoreResult;
}
});
}}
>
もっと
</Button>
</div>
</div>
)}
when i try it inside the map function like :
{query === name ? <td> {name}</td> : null }
it works fine but i don't know how to deal with the rows and that logic .

How to display data with id React Js and Firebase

I'm working on a project, and I would like to display some data from my firebase database,
I can show some of them, but I want to display the rest of the data of my "listClients" on a box, linked to the checkbox with the id.
listClients.js it's where i map the data from the db
import React, { Component } from "react";
import * as firebase from "firebase";
import { Table, InputGroup } from "react-bootstrap";
class ListClients extends React.Component {
state = {
loading: true
};
componentWillMount() {
const ref = firebase.database().ref("listClients");
ref.on("value", snapshot => {
this.setState({ listClients: snapshot.val(), loading: false });
});
}
render() {
if (this.state.loading) {
return <h1>Chargement...</h1>;
}
const clients = this.state.listClients.map((client, i) => (
<tr key={i}>
<td>
<input id={client.id} type="checkbox" onChange={this.cbChange} />
</td>
<td>{client.nom}</td>
<td>{client.prenom}</td>
</tr>
));
const clientsAdresses = this.state.listClients.map((clientAdresse, i) => (
<tr key={i}>
<td id={clientAdresse.id}>{clientAdresse.adresse}</td>
</tr>
));
return (
<>
<Table className="ContentDesign" striped bordered hover>
<thead>
<tr>
<th></th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>{clients}</tbody>
</Table>
<Table className="ContentDesign" striped bordered hover>
<thead>
<tr>
<th>Adresse : </th>
</tr>
</thead>
<tbody>{clientsAdresses}</tbody>
</Table>
</>
);
}
}
export default ListClients;
my data :
I only want the "adresse" of the id where the checkbox is check
Thank you
ERROR :
To retrieve the adresse from the database then use the following code:
componentWillMount() {
const ref = firebase.database().ref("listClients");
ref.on("value", snapshot => {
snapshot.forEach((subSnap) => {
let address = subSnap.val().adresse;
});
});
}
First add a reference to node listClients the using forEach you can iterate and retrieve the adresse
If you want to get the adresse according to the id, then you can use a query:
const ref = firebase.database().ref("listClients").orderByChild("id").equalTo(0);

not able to filter array to get movies on react app

I have a function called handleDelete that takes in a movie object and will filter based on which movie is passed. When I click it, I get the error Cannot read property 'filter' of undefined.
Update: Posted all of the code.
JS
handleDelete = (movie) => {
const movies = this.setState.movies.filter(m => m._id !== movie._id);
this.setState({ movies });
};
JSX
import React, { Component } from "react";
import "../services/fakeMovieService";
import { getMovies } from "../services/fakeMovieService";
class MovieTable extends Component {
state = {
movies: getMovies()
};
render() {
return (<table className="table">
<thead>
<tr>
<th scope="col">Title</th>
<th scope="col">Genre</th>
<th scope="col">Stock</th>
<th scope="col">Rate</th>
<th> </th>
</tr>
</thead>
<tbody>
{this.state.movies.map(movies => (
<tr key={movies._id}>
<td> {movies.title} </td>
<td> {movies.genre.name}</td>
<td> {movies.numberInStock} </td>
<td> {movies.dailyRentalRate}</td>
<td
onClick={movie => this.handleDelete(movie)}
className="btn btn-danger btn-sm"
>
Delete
</td>
</tr>
))}
</tbody>
</table>);
}}
export default MovieTable;
Movies array
const movies = [ {
_id: "5b21ca3eeb7f6fbccd471815",
title: "Terminator",
genre: { _id: "5b21ca3eeb7f6fbccd471818", name: "Action" },
numberInStock: 6,
dailyRentalRate: 2.5,
publishDate: "2018-01-03T19:04:28.809Z"
}];
It looks like you made a typo this.setState.movies.filter should be this.state.movies.filter so :
handleDelete = movie => {
const movies = this.state.movies.filter(m => m._id !== movie._id);
this.setState({ movies });
};
Without more context I'm assuming your issue is how you a referencing handleDelete. My primary assumption is that you aren't binding handleDelete to this in the constructor when using a smart component.
class MyComp extends React.Component {
constructor(props) {
super(props);
this.state = {
movies: null,
};
this.handleDelete = this.handleDelete.bind(this);
}
handleDelete = movie => {
const movies = this.setState.movies.filter(m => m._id !== movie._id);
this.setState({ movies });
}
render() {
return (<td
onClick={movie => this.handleDelete(this.props.movie)}
className="btn btn-danger btn-sm">
Delete
</td>);
}
}

Categories

Resources