I'm working on React booking website, connected to my backend by Rest API using axios and redux. Now I'm trying to show up the personal reservations and rooms for each user loaded, but I can't figure out why my user data aren't visible from my component and I can't reach the user ID by my props.
The code returns this error every time I try to load on componentDidMount the ID: Cannot read property '_id' of null, and my redux state is something like this (with user data nested in "user"):
Here's my redux and dashboard component:
//REDUX
const initialState = {
token: localStorage.getItem("token"),
isAuth: null,
isLoading: false,
user: null,
user_id: "",
};
export default function foo(state = initialState, action) {
switch (action.type) {
case USER_LOADING:
return {
...state,
isLoading: true,
};
case USER_LOADED:
return {
...state,
isAuth: true,
isLoading: false,
user: action.payload,
};
default:
return state;
}
}
//Dashbaord
import React, { Component } from "react";
import { Link } from "react-router-dom";
import moment from "moment";
import { Button, Table, Modal, ModalHeader, ModalBody } from "reactstrap";
import { connect } from "react-redux";
import {
getRooms,
setUserIDRooms,
filteredUserRooms,
deleteRoom,
} from "../actions/itemActions";
import { getReservations, filterReservation } from "../actions/bookAction";
import PropTypes from "prop-types";
import TopCont from "../components/TopCont";
import TabNav from "../components/TabNav";
import Tab from "../components/Tab";
import AddRoom from "../components/AddRoom";
import profile from "../images/unnamed.png";
/*
TODO:
1.fetch stanze by id utente!!
2.fatchare prenotazioni by id!!
*/
class Dashboard extends Component {
state = {
modal: false,
user_id: "",
book_user_id: "",
};
componentDidMount = () => {
this.setState({
user_id: this.props.auth.user._id,
book_user_id: this.props.auth.user._id,
});
console.log(this.state);
};
//Tab
constructor(props) {
super(props);
this.state = {
selected: "Prenotazioni",
};
}
setSelected = (tab) => {
this.setState({ selected: tab });
};
//Modal
toggle = (id) => () => {
this.setState((prevState) => ({
modal: prevState.modal === id ? null : id,
}));
};
closeModal = () => {
this.setState({
modal: !this.state.modal,
});
};
onDeleteClick = (_id) => {
this.props.deleteRoom(_id);
this.closeModal();
};
render() {
const { rooms } = this.props.room;
const { reservations } = this.props.reservation || {};
const { isAuth, user } = this.props.auth;
const DashUnauth = (
<>
<TopCont>
<div className="unauth-dashboard">
<h1>Questa è un'area riservata.</h1>
<Link className="btn-primary" to="/signin">
Accedi
</Link>
<Link className="btn-primary" to="/signup">
Registrati
</Link>
</div>
</TopCont>
</>
);
const DashBasic = (
<>
<div className="dash-cont">
<img src={profile} alt="profilo" className="profile-img" />
<div className="profile-stuff">
<h1>Ciao </h1>
<h3>Bentornato nella tua dashboard.</h3>
<h3>
Da qui puoi accedere alla gestione delle tue prenotazioni e tante
altre funzionalità.
</h3>
<Button onClick={this.onClick}>Aggiorna ID</Button>
</div>
</div>
<div className="tab-cont">
<TabNav
tabs={["Prenotazioni", "Strutture Caricate"]}
selected={this.state.selected}
setSelected={this.setSelected}
>
<Tab isSelected={this.state.selected === "Prenotazioni"}>
<Table hover>
<thead>
<tr>
<th>Struttura</th>
<th>Ospiti</th>
<th>CheckIn</th>
<th>CheckOut</th>
<th>Prezzo /notte</th>
</tr>
</thead>
{reservations.map(
(_id, room_name, ospiti, checkin_date, checkout_date) => (
<tbody>
<tr key={_id}>
<td>{room_name} </td>
<td>{ospiti}</td>
<td>{moment(checkin_date).format("DD/MM/YYYY")}</td>
<td>{moment(checkout_date).format("DD/MM/YYYY")}</td>
<td>Prezzo$</td>
</tr>
</tbody>
)
)}
</Table>
</Tab>
<Tab isSelected={this.state.selected === "Strutture Caricate"}>
<div className="tab-cont-button">
<Button>
<Link to="/profile-upgrade">Diventa Oste</Link>
</Button>
</div>
</Tab>
</TabNav>
</div>
</>
);
const DashPlus = (
<>
<div className="dash-cont">
<img src={profile} alt="profilo" className="profile-img" />
<div className="profile-stuff">
<h1>Ciao </h1>
<h3>Bentornato nella tua DashboardPlus.</h3>
<h3>
Da qui puoi accedere alla gestione delle tue prenotazioni, gestire
i tuoi annunci e tante altre funzionalità.
</h3>
<h1>Il tuo saldo: SPICCIULATO $</h1>
</div>
</div>
<div className="tab-cont">
<TabNav
tabs={["Prenotazioni", "Strutture Caricate", "Aggiungi Struttura"]}
selected={this.state.selected}
setSelected={this.setSelected}
>
<Tab isSelected={this.state.selected === "Prenotazioni"}>
<Table hover>
<thead>
<tr>
<th>Struttura</th>
<th>Luogo</th>
<th>CheckIn</th>
<th>Prezzo /notte</th>
<th>Totale</th>
</tr>
</thead>
{reservations.map(
(_id, room_name, ospiti, checkin_date, checkout_date) => (
<tbody>
<tr key={_id}>
<td>{room_name} </td>
<td>{ospiti}</td>
<td>{moment(checkin_date).format("DD/MM/YYYY")}</td>
<td>{moment(checkout_date).format("DD/MM/YYYY")}</td>
<td>Prezzo$</td>
</tr>
</tbody>
)
)}
</Table>
</Tab>
<Tab isSelected={this.state.selected === "Strutture Caricate"}>
<Table hover>
<thead>
<tr>
<th>Struttura</th>
<th>Luogo</th>
<th>Data Inserimento</th>
<th>Prezzo /notte</th>
<th>Numero Prenotazioni</th>
<th></th>
</tr>
</thead>
{rooms.map(({ _id, name, where, prezzo, upload_date }) => (
<tbody>
<tr key={_id}>
<td>{name}</td>
<td>{where}</td>
<td>{moment(upload_date).format("DD/MM/YYYY")}</td>
<td>{prezzo}$</td>
<td>Prenotazioni</td>
<td>
<Button onClick={this.toggle(_id)}>×</Button>
<Modal
isOpen={this.state.modal === _id}
toggle={this.toggle(_id)}
>
<ModalHeader>Elimina Struttura</ModalHeader>
<ModalBody>
Sei sicuro di voler eliminare questa struttura?
</ModalBody>
<Button onClick={this.onDeleteClick.bind(this, _id)}>
Elimina
</Button>
<Button onClick={this.closeModal}>Annulla</Button>
</Modal>
</td>
</tr>
</tbody>
))}
</Table>
</Tab>
<Tab isSelected={this.state.selected === "Aggiungi Struttura"}>
<AddRoom />
</Tab>
</TabNav>
</div>
</>
);
return <>{isAuth ? (user.userPlus ? DashPlus : DashBasic) : DashUnauth}</>;
}
}
Dashboard.propTypes = {
getRooms: PropTypes.func.isRequired,
getReservations: PropTypes.func.isRequired,
room: PropTypes.object.isRequired,
reservation: PropTypes.object.isRequired,
auth: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
user_id: state.room.user_id,
book_user_id: state.reservation.book_user_id,
auth: state.auth,
user: state.auth.user,
room: state.room,
reservation: state.reservation,
});
export default connect(mapStateToProps, {
getRooms,
setUserIDRooms,
filteredUserRooms,
deleteRoom,
getReservations,
filterReservation,
})(Dashboard);
Someone could help me??
you forgot a switch for the cases
switch {
// cases
}
Related
Description
i'm working on reactjs and apollo client project. i'm also developing deleteUser feature. delete mutation is working but without modal confirmation. i want to add modal confirm when admin click delete button. it means, delete mutation is executed after admin click on button yes inside modals.
Problem
When i'm clicking delete user button, mutation delete is executed first than modal is show. and when i'm click "yes" button, it'll be refetching data.
Here's the code :
import React, { useState, useEffect } from "react";
import { Table, Button } from "react-bootstrap";
import { useMutation } from "#apollo/client";
import { GET_ALL_USERS } from "../../../gql/query";
import { DELETE_USER } from "../../../gql/mutation";
import ModalEdit from "../Modals/ModalEdit";
import ModalConfirm from "../../Common/Modals/ModalConfirm";
const TableUserInfo = ({ data, variables }) => {
const [showModal, setShowModal] = useState(false);
const [username, setUsername] = useState("");
const [isDeleting, setIsDeleting] = useState(false);
const handleShowModal = () => setShowModal(true);
const handleCloseModal = () => setShowModal(false);
const [deleteUser, { error, loading, refetch }] = useMutation(DELETE_USER);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error</p>;
if (
!data ||
!data.getAllUsers ||
!data.getAllUsers.rows ||
!data.getAllUsers.rows.length
) {
return <p className="text-center"> Tidak ada data tersedia </p>;
}
// delete user handler
const handleDelete = (userToDelete) => {
setIsDeleting( true );
deleteUser({
variables: { username: userToDelete },
update(cache, { data }) {
const { getAllUsers } = cache.readQuery({
query: GET_ALL_USERS,
variables,
});
cache.writeQuery({
query: GET_ALL_USERS,
variables,
data: {
getAllUsers: {
...getAllUsers,
totalItems: getAllUsers.totalItems - 1,
rows: getAllUsers.rows.filter((user) => user.username !== userToDelete)
}
}
});
},
onError: (error) => {
console.log(JSON.stringify(error, null, 2));
},
});
}
return (
<Table responsive>
<thead>
<tr>
<th>No</th>
<th>Nama Pengguna</th>
<th>Role Akun</th>
<th>Email</th>
<th>Tanggal Daftar</th>
<th>Status Akun</th>
<th>Pengaturan</th>
</tr>
</thead>
<tbody>
{data.getAllUsers.rows.map((user, index) => (
<tr key={user.username}>
<td>{index + 1}</td>
<td>{user.full_name}</td>
<td>{user.group_id}</td>
<td>{user.email}</td>
<td>{user.created_dtm}</td>
<td>{user.status}</td>
<td>
{user.status !== "ACTIVE"
? [
<Button
key="Aktifkan Akun"
className="d-block mb-2 text-white bg-secondary w-100"
>
Aktifkan Akun
</Button>,
<Button
key="Ganti Role Akun"
className="d-block mb-2 btn-block btn-sm w-100"
disabled
>
Ganti Role Akun
</Button>,
]
: user.group_id === "admin"
? [
<Button
key="Ganti Role Akun"
variant="outline-success"
className="d-block btn-sm mb-2 w-100"
>
Ganti Role Akun
</Button>,
]
: [
<Button
key="Pilih Role Akun"
className="d-block btn-sm mb-2 w-100"
>
Pilih Role Akun
</Button>,
]}
<Button
key="Edit"
variant="outline-primary"
onClick={() => {
setShowModal(true);
setUsername(user.username);
}}
className="d-block btn-block btn-sm mb-2 w-100"
>
Edit
</Button>
<Button
key="Hapus"
variant="outline-danger"
onClick={() => {
handleDelete(user.username)}
}
disabled={loading}
className="d-block btn-block btn-sm mb-2 w-100"
>
Hapus
</Button>
</td>
</tr>
))}
</tbody>
{showModal ? (
<ModalEdit
show={handleShowModal}
onClose={handleCloseModal}
username={username}
/>
) : isDeleting ? ( <ModalConfirm
show={ isDeleting }
onHide= { () => { handleCloseModal(); setIsDeleting(false); } }
handleDelete={ handleDelete }
userToDelete={ username } />
) : null}
</Table>
);
};
export default TableUserInfo;
Question
How to fix the error and make data user is delete when admin click "yes" in modals ?
any help will be appreciated, thankyou.
I have this code to add div to table onclick, but I have added it from Stack to a Fuse project which has its own template. Please have a look at this code, I think there is a very simple problem with it. I am new to React, and I don't understand, how can I export the class. Whatever I tried, there is an error on it. Here is the code:
const useStyles = makeStyles({
layoutRoot: {},
});
Class Mdf extends React.Component ({
getInitialState: function () {
return {
tablerows: [
{ fname: "Tom", lname: "Moody", age: 23 }
]
};
},
addRow: function () {
// add new data from here
var newdata = { fname: "Tom", lname: "Moody", age: 23 }
//take the existing state and concat the new data and set the state again
this.setState({ tablerows: this.state.tablerows.concat(newdata) });
},
rows: function () {
return this.state.tablerows.map(function (row, i) {
return (<tr key={i}>
<td>{row.fname}</td>
<td>{row.lname}</td>
<td>{row.age}</td>
</tr>);
});
},
render: function () {
const classes = useStyles();
return (
<FusePageSimple
classes={{
root: classes.layoutRoot,
}}
header={
<div className="p-24">
<h1>Site Details</h1>
</div>
}
contentToolbar={
<div className="px-24">
<h4>Content Toolbar22222</h4>
</div>
}
content={
<div className="p-24">
<div>
<table>
<tr>
<td> row 1 </td>
</tr>
<tr>
<td> row 2 </td>
</tr>
<tr>
<td> row 3 </td>
</tr>
{this.rows()}
</table>
<button id="addBtn" onClick={this.addRow}>ADD</button>
</div>
</div>
}
/>
);
}
});
// React.render(<Mdf />)
export default Mdf
And the error message which shows up is this:
Attempted import error: './Mdf' does not contain a default export (imported as 'Mdf').
I'd like to, when a user deletes on row, for only that row to be deleted. Currently that only happens sometimes. And when you have only two items left to delete, when you click on the delete button, the row's data toggles and replaces itself. It doesn't actually delete.
mainCrud.js - houses the add and delete
crudAdd.js - defines state, event handlers, renders the form itself
crudTable.js - maps pre-defined rows defined in mainCrud.js, renders the table itself
Link to CodeSandbox (tables are under campaigns, dev and news tabs).
Any idea what could be causing this?
MainCrud.js
import React, { useState } from "react";
import CrudIntro from "../crud/crudIntro/crudIntro";
import CrudAdd from "../crud/crudAdd/crudAdd";
import CrudTable from "../crud/crudTable/crudTable";
const MainCrud = props => {
// Project Data
const projectData = [
{
id: 1,
name: "Skid Steer Loaders",
description:
"To advertise the skid steer loaders at 0% financing for 60 months.",
date: "February 1, 2022"
},
{
id: 2,
name: "Work Gloves",
description: "To advertise the work gloves at $15.",
date: "February 15, 2022"
},
{
id: 3,
name: "Telehandlers",
description: "To advertise telehandlers at 0% financing for 24 months.",
date: "March 15, 2022"
}
];
const [projects, setProject] = useState(projectData);
// Add Project
const addProject = project => {
project.id = projectData.length + 1;
setProject([...projects, project]);
};
// Delete Project
const deleteProject = id => {
setProject(projectData.filter(project => project.id !== id));
};
return (
<div>
<section id="add">
<CrudIntro title={props.title} subTitle={props.subTitle} />
<CrudAdd addProject={addProject} />
</section>
<section id="main">
<CrudTable projectData={projects} deleteProject={deleteProject} />
</section>
</div>
);
};
export default MainCrud;
CrudAdd.js
import React, { Component } from "react";
import "../crudAdd/crud-add.scss";
import "../../button.scss";
class CrudAdd extends Component {
state = {
id: null,
name: "",
description: "",
date: ""
};
handleInputChange = e => {
let input = e.target;
let name = e.target.name;
let value = input.value;
this.setState({
[name]: value
});
};
handleFormSubmit = e => {
e.preventDefault();
this.props.addProject({
id: this.state.id,
name: this.state.name,
description: this.state.description,
date: this.state.date
});
this.setState({
// Clear values
name: "",
description: "",
date: ""
});
};
render() {
return (
<div>
<form onSubmit={this.handleFormSubmit}>
<input
name="name"
type="name"
placeholder="Name..."
id="name"
value={this.state.name}
onChange={e => this.setState({ name: e.target.value })}
required
/>
<input
name="description"
type="description"
placeholder="Description..."
id="description"
value={this.state.description}
onChange={e => this.setState({ description: e.target.value })}
required
/>
<input
name="date"
type="name"
placeholder="Date..."
id="date"
value={this.state.date}
onChange={e => this.setState({ date: e.target.value })}
required
/>
<button type="submit" className="btn btn-primary">
Add Project
</button>
</form>
</div>
);
}
}
export default CrudAdd;
CrudTable.js
import React, { Component } from "react";
import "../crudTable/crud-table.scss";
class CrudTable extends Component {
render() {
const props = this.props;
return (
<div>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Project Name</th>
<th scope="col">Project Description</th>
<th scope="col">Date</th>
<th scope="col"> </th>
</tr>
</thead>
<tbody>
{props.projectData.length > 0 ? (
props.projectData.map(project => (
<tr key={project.id}>
<td>{project.name}</td>
<td>{project.description}</td>
<td>{project.date}</td>
<td>
<button className="btn btn-warning">Edit</button>
<button
onClick={() => props.deleteProject(project.id)}
className="btn btn-danger"
>
Delete
</button>
</td>
</tr>
))
) : (
<tr>
<td>No projects found. Please add a project.</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
);
}
}
export default CrudTable;
This is because you are filtering over projectData. Update your deleteProject method to filter over your React.useState projects variable and it will work.
const deleteProject = id => {
setProject(projects.filter(project => project.id !== id));
};
See code sandbox example here.
I want to filter a list table using axios to get the Name as you can see the figure :
When I try to filter it, it works well, but when I click on the delete button, this row will be deleted and I get : Unhandled Rejection (TypeError): Cannot read property 'filter' of undefined and when I click on the view button,I don't get the page of view.
My code is below :
class ListeLivs extends Component {
constructor(props) {
super(props);
this.state = {
clients: [],
search :"",
alert: null
};
this.handleView = this.handleView.bind(this);
this.handleEdit = this.handleEdit.bind(this);
this.delete = this.delete.bind(this)
this.onchange = this.onchange.bind(this)
componentDidMount() {
axios({
method: "get",
url: "/app/listeclients/",
withCredentials: true,
headers: {
"Content-Type": "application/json",
Accept: "application/json"
}
}).then(response => {
if (response && response.data) {
this.setState({ clients: response.data });
}
}).catch(error => console.log(error));
}
popupdel(Code) {
const getAlert = () => (<SweetAlert
warning
showCancel
confirmBtnText="Supprimer"
confirmBtnBsStyle="danger"
cancelBtnBsStyle="Annuler"
title="Êtes-vous sûr de supprimer ce client ?"
onConfirm={() => this.delete(Code)}
onCancel={() => this.onCancel()} >
Vous ne pouvez pas restaurer ce client !
</SweetAlert>);
this.setState({
alert: getAlert()
});
}
onCancel() {
this.setState({
alert: null
});
}
delete(Code) {
axios.delete('http://localhost:4000/app/deleteclient/' + Code).then(function(clients) {
this.setState({
clients: clients.records
});
this.setState({
alert: null
});
/*swal("Êtes-vous sûr de supprimer ce client ?", {
buttons: ["Annuler", "Supprimer"],*/
window.location.reload()
}.bind(this));
}
onchange = (e) => {
this.setState({ search: e.target.value });
}
handleView(Code) {
try {
console.log("Voir client")
this.props.history.push('/clients/viewclient/' + Code);
}
catch (error) {
this.setState({ error });
}
}
catch (error) {
this.setState({ error });
}
}
render() {
let { clients } = this.state;
const { search } = this.state;
}
const filteredClients = clients.filter( client =>{
return client.Prenom.toLowerCase().indexOf( search.toLowerCase() ) !== -1
})
return (<div className="animated fadeIn">
<Card style={{ height:"auto"}}>
<CardHeader>
<h4>
<strong>
<i className="fa fa-align-justify" /> Tous les clients
<InputGroup style={{ float:"right", width:"250px"}}>
<Input onChange={this.onchange} type="search"/>
<InputGroupAddon addonType="prepend">
<InputGroupText><i className="fa fa-search" aria-hidden="true"></i></InputGroupText>
</InputGroupAddon>
</InputGroup>
</strong>
</h4>
</CardHeader>
<CardBody>
<Table bordered responsive size="sm" style={center} hover>
<thead >
<tr>
<th ><strong>Code</strong></th>
<th scope="col">Prenom</th>
<th scope="col">Nom</th>
<th scope="col">Email</th>
<th scope="col">Telephone</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
{
filteredClients.map( client =>
<tr key={client.Code}>
<th scope="row">{client.Code}</th>
<td>{client.Prenom}</td>
<td>{client.Nom}</td>
<td>{client.Email}</td>
<td>{client.Telephone}</td>
<td><button style={btn} onClick={(Code) =>this.handleView(client.Code) } type="button"><i class="fa fa-eye"></i></button>
<button style={btn} onClick={(Code)=>this.handleEdit(client.Code)} type="button"><i class="fa fa-edit"></i></button>
<button style={btn} onClick={(Code) => this.popupdel(client.Code)} type="button"><i class="fa fa-trash-o"></i>
</button>
{this.state.alert}
</td>
</tr>
)}
</tbody>
</Table>
</CardBody>
</Card>
</div>);
}
}
export default ListeClients;
How can I fix that ?
It looks like the result returned by /app/deleteclient/is not an array.
You need to make sure that it is an array.
delete(Code) {
axios.delete('http://localhost:4000/app/deleteclient/' + Code).then(function(clients) {
this.setState({
clients: clients.records || []
});
I have a problem. I'm lost in the deep forest of reactJs. I'm new here.
I have 8 components which I need to get via clicking on short-name button .
What are the steps.
I select what I need from the first filter and I get short_names and all the components without data.
I don't want to get all the components, i need just 1 component that I'll get by clicking on a short name.
Screenshot here
Here is code of rendering page:
import React, { Component } from 'react';
import { Link } from 'react-router';
import { getAll, getAllRates } from '../actions';
import { MODULE_NAME } from './index';
import { PanelHeader, PanelFooter, LocalFilter } from 'Components';
import locales from 'Shared/locales';
import search from 'Shared/search';
import sortBy from 'Shared/sortBy';
import { AvsProviders, FakProviders, LaaProviders, Laac1Providers,
Laac2Providers, Laac3Providers, MpgProviders, Mpg2Providers } from '../ComponentsProviders';
export default class ListsAccounting extends Component {
state = {
data: [],
le_id: null,
year: new Date().getFullYear(),
totalPages: 0,
searchString: '',
limit: '50',
page: 1,
};
search = search(this);
sortBy = sortBy(this);
loadData = (params) => {
const { searchString } = this.state;
const q = searchString === '' ? null : searchString;
getAll({ leId: this.state.le_id, name: MODULE_NAME, params: { q, year: this.state.year, ...params } })
.then(success => this.setState({
data: success.data,
totalPages: success.totalPages,
page: success.page,
limit: String(success.limit || ''),
}));
};
constructor() {
super();
this.onClick = this.handleClick.bind(this);
}
handleClick(event) {
const { id } = event.target;
console.log(id);
}
getData = (leId, id, type, year) => {
getAllRates({ leId, id, type, year, name: MODULE_NAME })
.then(() => this.loadData());
};
changeState = state => this.setState(state, () => this.loadData());
render() {
const { limit, totalPages, data } = this.state;
console.log(this);
return (
<div className="container">
<div className="row">
<div className="col-xs-12 col-sm-12 col-md-6">
<div className="panel panel-adminme table-dynamic">
<PanelHeader
name="insurances"
currentState={{
state: this.state,
loadData: this.loadData,
}}
/>
<div className="table-filters">
<div className="row no-x-margin">
<div className="col-sm-4 col-xs-6">
<LocalFilter
name="all-providers-leg-entities"
placeholder="le_id"
option="le_id"
value={this.state.le_id}
changeState={this.changeState}
/>
</div>
<div className="col-md-3 col-sm-4 col-xs-6">
<LocalFilter
name="insurance-years"
placeholder="year"
option="year"
value={this.state.year}
changeState={this.changeState}
/>
</div>
</div>
</div>
<div className="table-responsive">
<table className="table table-bordered table-striped table-hover">
<thead>
<tr className="text-center">
<th>
NAME
</th>
<th>
SHORT_NAME
</th>
<th>
ACTION
</th>
</tr>
</thead>
<tbody>
{
!data.length &&
<tr>
<td colSpan="3" className="text-center">
{locales('no_rows')}
</td>
</tr>
}
{
data.map((row, index) => (
<tr key={`${MODULE_NAME}-${index}`}>
<td>
<h5>{row.type}</h5>
</td>
<td>
{
row.text.map((name, indexText) => (
<span key={name} className="margin-right-10">
<Link
key={row.type}
role="button"
onClick={ () => this.getData(
this.state.le_id,
row.text_id[indexText],
row.type,
row.year,
)}
>
{name}
</Link>
</span >
))
}
</td>
<td className="btn btn-info">
ADD
</td>
</tr>
))
}
</tbody>
</table>
</div>
<PanelFooter
limit={limit}
totalPages={totalPages}
loadData={this.loadData}
/>
</div>
</div>
<div className="col-xs-12 col-sm-12 col-md-6">
{ data.type === data.type && data.text_id === data.text_id &&
data.map((row) => {
console.log(row.type);
switch (row.type) {
case 'AVS':
return (
<AvsProviders/>
);
case 'FAK' :
return (
<FakProviders/>
);
case 'LAA':
return (
<LaaProviders/>
);
case 'LAAC1':
return (
<Laac1Providers/>
);
case 'LAAC2':
return (
<Laac2Providers/>
);
case 'LAAC3':
return (
<Laac3Providers/>
);
case 'MPG':
return (
<MpgProviders/>
);
case 'MPG2':
return (
<Mpg2Providers/>
);
default:
return null;
}
})
}
</div>
</div>
</div>
);
}
}
Here is page of 1 of the rendering components:
import React, { Component } from 'react';
import { getAllRates } from '../../actions';
import { PanelHeader } from 'Components';
const MODULE_NAME = 'FAK';
export default class FakProviders extends Component {
state = {
data: [],
le_id: null,
year: new Date().getFullYear(),
totalPages: 0,
searchString: '',
limit: '50',
page: 1,
};
componentDidMount() {
this.loadData();
}
loadData = (params) => {
const { searchString } = this.state;
const q = searchString === '' ? null : searchString;
getAllRates({ leId: this.props.params.le_id,
id: this.props.params.text_id,
name: MODULE_NAME,
params: { q, ...params } })
.then(success => this.setState({
data: success.data,
totalPages: success.totalPages,
page: success.page,
limit: String(success.limit || ''),
}));
};
changeState = state => this.setState(state, () => this.loadData());
render() {
const { data } = this.state;
return (
<div className="panel panel-adminme table-dynamic">
<PanelHeader
name="insurances"
currentState={{
search: this.search,
state: this.state,
loadData: this.loadData,
}}
/>
<div className="table-responsive">
<table className="table table-bordered table-striped table-hover">
<thead>
<tr>
<th>
<h4>{data.fak_short_name}</h4>
</th>
<th>
<h4>{data.year}</h4>
</th>
</tr>
</thead>
<tbody>
<tr>
<th>
<h4>fak_rate_ee</h4>
</th>
<th>
<h4>
{data.fak_rate_ee}
</h4>
</th>
</tr>
<tr>
<th>
<h4>fak_rate_er</h4>
</th>
<th>
<h4>
{data.fak_rate_er}
</h4>
</th>
</tr>
</tbody>
</table>
</div>
<div className="panel-footer" />
</div>
);
}
}