How to properly display JSON result in a table via ReactJS - reactjs

I have this code which fetches data from an API and displays JSON response in a div. How do I display the JSON response in a table?
This is how I display it in div via status.jsx:
// some codings
render() {
const { status, isLocal } = this.props;
if(!isLocal()) {
return (
<div className="status">
<div className="status-text">
<b>Status</b> {status.text}<br />
<b>Title</b> status.textTitle} <br />
<b>Event</b> {status.textEvent}
</div>
</div>
)
}
}
I have tried displaying it in a table as per below but could not get it to be aligned properly
//some codings
render() {
const { status, isLocal } = this.props;
if(!isLocal()) {
return (
<table>
<tbody>
<th>Status</th>
<th>Title</th>
<th>Event</th>
<tr>
<td>{status.text} </td>
<td>{status.textTitle} </td>
<td>{status.textEvent}</td>
<td><button
className="btn btn-danger status-delete"
onClick={this.toggleDeleteConfirmation}
disabled={this.state.showDeleteConfirmation}
>
Delete
</button></td>
</tr></tbody>
</table>
)
}
}
Here is profile.jsx:
import React, { Component } from 'react';
import {
isSignInPending,
loadUserData,
Person,
getFile,
putFile,
lookupProfile
} from 'bs';
import Status from './Status.jsx';
const avatarFallbackImage = 'https://mysite/onename/avatar-placeholder.png';
const statusFileName = 'statuses.json';
export default class Profile extends Component {
constructor(props) {
super(props);
this.state = {
person: {
name() {
return 'Anonymous';
},
avatarUrl() {
return avatarFallbackImage;
},
},
username: "",
statuses: [],
statusIndex: 0,
isLoading: false
};
this.handleDelete = this.handleDelete.bind(this);
this.isLocal = this.isLocal.bind(this);
}
componentDidMount() {
this.fetchData()
}
handleDelete(id) {
const statuses = this.state.statuses.filter((status) => status.id !== id)
const options = { encrypt: false }
putFile(statusFileName, JSON.stringify(statuses), options)
.then(() => {
this.setState({
statuses
})
})
}
fetchData() {
if (this.isLocal()) {
this.setState({ isLoading: true })
const options = { decrypt: false, zoneFileLookupURL: 'https://myapi/v1/names/' }
getFile(statusFileName, options)
.then((file) => {
var statuses = JSON.parse(file || '[]')
this.setState({
person: new Person(loadUserData().profile),
username: loadUserData().username,
statusIndex: statuses.length,
statuses: statuses,
})
})
.finally(() => {
this.setState({ isLoading: false })
})
} else {
const username = this.props.match.params.username
this.setState({ isLoading: true })
lookupProfile(username)
.then((profile) => {
this.setState({
person: new Person(profile),
username: username
})
})
.catch((error) => {
console.log('could not resolve profile')
})
const options = { username: username, decrypt: false, zoneFileLookupURL: 'https://myapi/v1/names/'}
getFile(statusFileName, options)
.then((file) => {
var statuses = JSON.parse(file || '[]')
this.setState({
statusIndex: statuses.length,
statuses: statuses
})
})
.catch((error) => {
console.log('could not fetch statuses')
})
.finally(() => {
this.setState({ isLoading: false })
})
}
}
isLocal() {
return this.props.match.params.username ? false : true
}
render() {
const { handleSignOut } = this.props;
const { person } = this.state;
const { username } = this.state;
return (
!isSignInPending() && person ?
<div className="container">
<div className="row">
<div className="col-md-offset-3 col-md-6">
{this.isLocal() &&
<div className="new-status">
Hello
</div>
}
<div className="col-md-12 statuses">
{this.state.isLoading && <span>Loading...</span>}
{
this.state.statuses.map((status) => (
<Status
key={status.id}
status={status}
handleDelete={this.handleDelete}
isLocal={this.isLocal}
/>
))
}
</div>
</div>
</div>
</div> : null
);
}
}

Related

Access to api response data

My code pass in a search term and the promise api call returns one record and the data format is as below:
` json api data
0:
{
id:"aff3b4fa-bdc0-47d1-947f-0163ff5bea06"
keyword: somekeyword
URL:"mypage.html"
}
I need to retrieve the URL value, so I try to get URL by using response.data[0].URL. But I receive the error "Unhandled Rejection (TypeError): response.data[0] is undefined". How do I get the URL value? Thanks.
` autocomplete.js
export class Autocomplete extends Component {
state = {
activeSuggestion: 0,
filteredSuggestions: [],
showSuggestions: false,
userInput: "",
suggestions: [],
results: [],
URL: "",
};
componentDidMount() {
this.GetPrograms();
const { userInput } = this.state;
//this.runSearch();
}
GetPrograms = () => {
axios
.get("https://mydomain/GetPrograms/")
.then((response) => {
this.setState({ suggestions: response.data });
});
};
runSearch = async () => {
const response = await axios.get(
"https://mydomain/api/get",
{
params: {
searchTerm: this.state.userInput,
},
}
);
let results = response.data;
console.log("response", results);
this.setState({ results: results, URL: response.data[0].URL });
window.location.href =
"https://mydomain/" + this.state.URL;
};
onChange = (e) => {
const { suggestions } = this.state; //this.props;
const userInput = e.currentTarget.value;
const filteredSuggestions = suggestions.filter(
(suggestion) =>
suggestion.toLowerCase().indexOf(userInput.toLowerCase()) > -1
);
this.setState({
activeSuggestion: 0,
filteredSuggestions,
showSuggestions: true,
userInput: e.currentTarget.value,
});
};
onClick = (e) => {
this.setState({
activeSuggestion: 0,
filteredSuggestions: [],
showSuggestions: false,
userInput: e.currentTarget.innerText,
});
this.onSearch();
console.log(
"child component clicked and value=" + e.currentTarget.innerText
);
};
onKeyDown = (e) => {
const { activeSuggestion, filteredSuggestions } = this.state;
if (e.keyCode === 13) {
this.setState({
activeSuggestion: 0,
showSuggestions: false,
userInput: filteredSuggestions[activeSuggestion],
});
} else if (e.keyCode === 38) {
if (activeSuggestion === 0) {
return;
}
this.setState({ activeSuggestion: activeSuggestion - 1 });
} else if (e.keyCode === 40) {
if (activeSuggestion - 1 === filteredSuggestions.length) {
return;
}
this.setState({ activeSuggestion: activeSuggestion + 1 });
}
//this.setState({ searchTerm: e.currentTarget.value });
console.log("userinput:" + this.state.userInput);
};
render() {
const {
onChange,
onClick,
onKeyDown,
onKeyPress,
state: {
activeSuggestion,
filteredSuggestions,
showSuggestions,
userInput,
},
} = this;
let suggestionsListComponent;
if (showSuggestions && userInput) {
if (filteredSuggestions.length) {
suggestionsListComponent = (
<ul class="suggestions">
{filteredSuggestions.map((suggestion, index) => {
let className;
if (index === activeSuggestion) {
className = "";
}
return (
<li key={suggestion} onClick={onClick}>
{suggestion}
</li>
);
})}
</ul>
);
} else {
suggestionsListComponent = (
<div class="no-suggestions">
<em>No suggestions</em>
</div>
);
}
}
return (
<div>
<input
id="search-box"
placeholder="Search..."
type="search"
onChange={onChange}
onKeyDown={onKeyDown}
value={userInput}
/>
{suggestionsListComponent}
</div>
);
}
}
export default Autocomplete;
`
The api call returns 0 record that causes the error.

Delete single row in sqlite DB with react and express

As the title said, im trying to delete a single user with a click on the button in the Table. But it deletes all users. So i think i have to map the single id´s to the button. But how?
This is my first CRUD App, so im not that experienced yet.
here is my React userTable component:
import React, { Component } from 'react'
const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT
class Userstable extends Component {
constructor(props) {
super(props)
this.state = {
users: [],
isLoading: false,
isError: false
}
}
async componentDidMount() {
this.setState({ isLoading: true })
const response = await fetch(`${API_ENDPOINT}/api/users`)
if (response.ok) {
const users = await response.json()
this.setState({ users, isLoading: false })
} else {
this.setState({ isError: true, isLoading: false })
}
}
render() {
const { users, isLoading, isError } = this.state
if (isLoading) {
return <div>Loading...</div>
}
if (isError) {
return <div>Error</div>
}
return users.length > 0
? (
<table className="table" id="tblData" >
<thead>
<tr>
<th style={{ borderTopLeftRadius: "4px" }}>ID</th>
<th>Name</th>
<th>email</th>
<th style={{ borderTopRightRadius: "4px" }}></th>
</tr>
</thead>
<tbody>
{this.renderTableRows()}
</tbody>
</table>
) : (
<div>
No users.
</div>
)
}
renderTableHeader = () => {
return Object.keys(this.state.users[0]).map(attr =>
<th key={attr} >
{attr}
</th>)
}
deleteTableRow = () => {
return this.state.users.map(user => {
return (
fetch(`${API_ENDPOINT}/api/users/${user.id}`, {method: 'DELETE'})
)
})
}
renderTableRows = () => {
return this.state.users.map(user => {
return (
<tr key={user.id}>
<td>{user.id}</td>
<td>{user.regname}</td>
<td>{user.regemail}</td>
<td className="delButton" onClick={this.deleteTableRow}>✕</td>
</tr>
)
})
}
}
export default Userstable
and here is my express Backend route:
router.delete("/users/:id", (req, res, next) => {
var sql = "DELETE FROM Users WHERE id = ?"
var params = [req.params.id]
db.run (sql, params, (err) => {
if (err) {
res.status(400).json({ "error": res.message })
return;
}
res.status(200)
res.json({ "answer": "success" })
return
});
});
thanks!
You can pass the id in onClick:
<td className="delButton" onClick={() => this.deleteTableRow(user.id)}>✕</td>
and send the request with the id:
deleteTableRow = (id) => {
fetch(`${API_ENDPOINT}/api/users/${id}`, {method: 'DELETE'})
}

Updating state in react using componentDidUpdate

I cannot get the state to update in my code
I am having an issue wiith my componentDidUpdate() which does not update the state of assignments after making an API call
when updating assignments. When I update the expiration date of a particular assignment in my list, it makes an API call to the server and returns
true if the response succeeds. The only way to see the update change in the state is to refresh the page. componentDidUpdate()
is stuck in an infinite loop, can anyone identify the underlining cause for this?
Thanks for any help
import * as React from 'react';
import './BundleAssignments.less';
import { IBundles, featureAccessApi, IAssignmentsByFirm, IBundleAssignment } from '#afi/tfs';
import { Loader } from '#afi/tfs';
export interface IOwnProps {}
export interface IOwnState {
loadingBundles: boolean,
loadingAssignments?: boolean,
loadingUpdate?: boolean,
bundles: IBundles[],
assignments: IAssignmentsByFirm[],
expirationDate: string,
bundleId?: number | undefined
}
export class BundleAssignments extends React.Component<IOwnProps, IOwnState> {
constructor(props: IOwnProps) {
super(props);
this.state = {
loadingBundles: true,
bundles: [],
assignments: [],
expirationDate: "",
bundleId: undefined
};
}
public componentDidMount() {
this.loadBundles();
}
public componentDidUpdate(prevProps: IOwnProps, prevState: IOwnState)
{
if (prevState.assignments !== this.state.assignments && this.state.bundleId !== undefined){
this.loadBundleAssignments(this.state.bundleId);
}
}
public render() {
return (
<div className="bundle-assignments">
<h1>Bundle assignments</h1>
{
this.state.loadingBundles ? <Loader /> :
<>
<select onChange={e => this.onChangeSelectedBundle(e)}>
<option value="">-- Select a Bundle --</option>
{
this.state.bundles.map(b =>
<option key={b.id} value={b.id}>{b.name}</option>
)
}
</select>
{
this.state.assignments != null && this.state.assignments.length > 0 ?
(this.state.loadingAssignments || this.state.loadingUpdate) ? <Loader /> :
<>
<h1>Assignments</h1>
<div className="download">
<a href={"https://localhost:44301/api/v2/admin/featureBundle/download/" + this.state.bundleId}>Download Excel</a>
</div>
<table className="assignmentsTable">
{
this.state.assignments.map(a =>
<tr key={a.firmRef}>
<th>
<span>{a.firmName}</span><br />
<a href={"admin/teams/firm/" + a.firmRef}>View teams</a>
</th>
<td>
{
<ul id="entites">
{
a.entities.map(e =>
<li key={e.entityRef}>
<span>{e.entityName}</span>
</li>
)
}
</ul>
}
</td>
<td>
{
a.entities.map(e =>
<form key={e.entityRef} onSubmit={(event) => this.handleSubmit(event, e.bundleAssignment.entityRef, e.bundleAssignment.bundleId, e.bundleAssignment.entityTypeId)}>
<input type="datetime-local" name="expirationDate" defaultValue={e.bundleAssignment.expirationDate} onChange={this.handleInputChange} />
<input type="submit" value="Update" />
</form>
)
}
</td>
</tr>
)
}
</table>
</>
: null
}
</>
}
</div>
)
}
private loadBundles = () => {
featureAccessApi.bundles()
.then(response => this.loadBundlesSuccess(response.bundles));
}
private loadBundlesSuccess = (bundles: IBundles[]) => {
this.setState({ ...this.state,
...{
loadingBundles: false,
bundles: bundles
}
})
}
private onChangeSelectedBundle = (e: React.ChangeEvent<HTMLSelectElement>) => {
const bundleId = Number(e.target.value);
this.setState({ ...this.state, ...{ loadingAssignments: true, bundleId: bundleId } })
this.loadBundleAssignments(bundleId);
}
private handleSubmit = (e: React.FormEvent, entityRef: number, bundleId: number, entityTypeId: number) => {
e.preventDefault();
this.setState({ ...this.state, ...{ loadingUpdate: true }})
this.updateBundleAssignment(entityRef, bundleId, entityTypeId);
}
private handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const target = e.target;
const value = target.value;
const name = target.name;
this.setState({ ...this.state,
...{
[name]: value
}
})
}
private updateBundleAssignment = (entityRef: number, bundleId: number, entityTypeId: number) => {
const request: IBundleAssignment = {
entityRef: entityRef,
bundleId: bundleId,
entityTypeId: entityTypeId,
expirationDate: this.state.expirationDate
};
featureAccessApi.updateBundleAssignment(request)
.then(response => this.bundleAssignmentUpdateSuccess());
}
private bundleAssignmentUpdateSuccess = () =>
this.setState({ ...this.state, ...{ loadingUpdate: false }})
private loadBundleAssignments = (bundleId: number) => {
featureAccessApi.bundleAssignments(bundleId)
.then(response => this.loadBundleAssignmentsSuccess(response.assignmentsByFirms));
}
private loadBundleAssignmentsSuccess = (bundleAssignments: IAssignmentsByFirm[]) => {
this.setState({ ...this.state,
...{
loadingAssignments: false,
assignments: bundleAssignments
}
})
}
}
Comparing arrays with !== will only compare the reference of the arrays and not their contents, so every time you update the assignment array, loadBundleAssignments will be run again.
console.log([1,2] !== [1,2])
You could instead use e.g. Lodash isEqual to check if all the elements in the arrays match each other.
public componentDidUpdate(prevProps: IOwnProps, prevState: IOwnState) {
if (
!_.isEqual(prevState.assignments, this.state.assignments) &&
this.state.bundleId !== undefined
) {
this.loadBundleAssignments(this.state.bundleId);
}
}

Reactjs: How to properly fetch each users record from database on pop button click using Reactjs

The code below shows each user info on users list button click.
Now I want fetch each users record from database on users list button click.
In the open() function, I have implemented the code below
open = (id,name) => {
alert(id);
alert(name);
//start axios api call
const user_data = {
uid: 'id',
uname: 'name'
};
this.setState({ loading_image: true }, () => {
axios.post("http://localhost/data.php", { user_data })
.then(response => {
this.setState({
chatData1: response.data[0].id,
chatData: response.data,
loading_image: false
});
console.log(this.state.chatData);
alert(this.state.chatData1);
})
.catch(error => {
console.log(error);
});
});
}
In class OpenedUser(), I have initialize in the constructor the code below
chatData: []
In the render method have implemented the code
<b> Load Message from Database for each user ({this.state.chatData1})</b>
<div>
{this.state.chatData.map((pere, i) => (<li key={i}>{pere.lastname} - {pere.id}----- {pere.username}</li>))}
</div>
Here is my Issue:
My problem is that the Axios Api is getting the result but am not seeing any result in the render method.
but I can see it in the console as per code below
Array(1)
0: {id: "1", firstname: "faco", lastname: "facoyo"}
length: 1
Here is an example of json api response.
[{"id":"1","firstname":"faco","lastname":"facoyo"}]
Here is the full code
import React, { Component, Fragment } from "react";
import { render } from "react-dom";
import { Link } from 'react-router-dom';
import axios from 'axios';
class User extends React.Component {
open = () => this.props.open(this.props.data.id, this.props.data.name);
render() {
return (
<React.Fragment>
<div key={this.props.data.id}>
<button onClick={() => this.open(this.props.data.id,this.props.data.name)}>{this.props.data.name}</button>
</div>
</React.Fragment>
);
}
}
class OpenedUser extends React.Component {
constructor(props) {
super(props);
this.state = {
chatData: [],
hidden: false,
};
}
componentDidMount(){
} // close component didmount
toggleHidden = () =>
this.setState(prevState => ({ hidden: !prevState.hidden }));
close = () => this.props.close(this.props.data.id);
render() {
return (
<div key={this.props.data.id} style={{ display: "inline-block" }}>
<div className="msg_head">
<button onClick={this.close}>close</button>
<div>user {this.props.data.id}</div>
<div>name {this.props.data.name}</div>
{this.state.hidden ? null : (
<div className="msg_wrap">
<div className="msg_body">Message will appear here</div>
<b> Load Message from Database for each user ({this.state.chatData1}) </b>
<div>
{this.state.chatData.map((pere, i) => (
<li key={i}>
{pere.lastname} - {pere.id}----- {pere.username}
</li>
))}
</div>
</div>
)}
</div>
</div>
);
}
}
class App extends React.Component {
constructor() {
super();
this.state = {
shown: true,
activeIds: [],
data: [
{ id: 1, name: "user 1" },
{ id: 2, name: "user 2" },
{ id: 3, name: "user 3" },
{ id: 4, name: "user 4" },
{ id: 5, name: "user 5" }
],
};
}
toggle() {
this.setState({
shown: !this.state.shown
});
}
open = (id,name) => {
alert(id);
alert(name);
//start axios api call
const user_data = {
uid: 'id',
uname: 'name'
};
this.setState({ loading_image: true }, () => {
axios.post("http://localhost/apidb_react/search_data.php", { user_data })
.then(response => {
this.setState({
chatData1: response.data[0].id,
chatData: response.data,
loading_image: false
});
console.log(this.state.chatData);
alert(this.state.chatData1);
})
.catch(error => {
console.log(error);
});
});
// end axios api call
this.setState((prevState) => ({
activeIds: prevState.activeIds.find((user) => user === id)
? prevState.activeIds
: [...prevState.activeIds, id]
}));
}
close = id => {
this.setState((prevState) => ({
activeIds: prevState.activeIds.filter((user) => user !== id),
}));
};
renderUser = (id) => {
const user = this.state.data.find((user) => user.id === id);
if (!user) {
return null;
}
return (
<OpenedUser key={user.id} data={user} close={this.close}/>
)
}
renderActiveUser = () => {
return (
<div style={{ position: "fixed", bottom: 0, right: 0 }}>
{this.state.activeIds.map((id) => this.renderUser(id)) }
</div>
);
};
render() {
return (
<div>
{this.state.data.map(person => (
<User key={person.id} data={person} open={this.open} />
))}
{this.state.activeIds.length !== 0 && this.renderActiveUser()}
</div>
);
}
}
The problem is you're making the request in the App component and storing in state but you're trying to access the state in a child component so it will never actually read the data.
To fix this you need to pass in the chat data via prop
<OpenedUser
chatData={this.state.chatData}
key={user.id}
data={user}
close={this.close}
/>
Note: In my runnable example, I've replaced your api endpoint with a mock api promise.
const mockApi = () => {
return new Promise((resolve, reject) => {
const json = [{ id: "1", firstname: "faco", lastname: "facoyo" }];
resolve(json);
});
};
class User extends React.Component {
open = () => this.props.open(this.props.data.id, this.props.data.name);
render() {
return (
<React.Fragment>
<div key={this.props.data.id}>
<button
onClick={() => this.open(this.props.data.id, this.props.data.name)}
>
{this.props.data.name}
</button>
</div>
</React.Fragment>
);
}
}
class OpenedUser extends React.Component {
constructor(props) {
super(props);
this.state = {
hidden: false
};
}
componentDidMount() {} // close component didmount
toggleHidden = () =>
this.setState(prevState => ({ hidden: !prevState.hidden }));
close = () => this.props.close(this.props.data.id);
render() {
return (
<div key={this.props.data.id} style={{ display: "inline-block" }}>
<div className="msg_head">
<button onClick={this.close}>close</button>
<div>user {this.props.data.id}</div>
<div>name {this.props.data.name}</div>
{this.state.hidden ? null : (
<div className="msg_wrap">
<div className="msg_body">Message will appear here</div>
<b>
{" "}
Load Message from Database for each user ({this.state.chatData1}
){" "}
</b>
<ul>
{this.props.chatData.map((pere, i) => (
<li key={i}>
{pere.lastname} - {pere.id}----- {pere.username}
</li>
))}
</ul>
</div>
)}
</div>
</div>
);
}
}
class App extends React.Component {
constructor() {
super();
this.state = {
shown: true,
chatData: [],
activeIds: [],
data: [
{ id: 1, name: "user 1" },
{ id: 2, name: "user 2" },
{ id: 3, name: "user 3" },
{ id: 4, name: "user 4" },
{ id: 5, name: "user 5" }
]
};
}
toggle() {
this.setState({
shown: !this.state.shown
});
}
open = (id, name) => {
alert(id);
alert(name);
//start axios api call
const user_data = {
uid: "id",
uname: "name"
};
// this.setState({ loading_image: true }, () => {
// axios
// .post("http://localhost/apidb_react/search_data.php", { user_data })
// .then(response => {
// this.setState({
// chatData1: response.data[0].id,
// chatData: response.data,
// loading_image: false
// });
// console.log(this.state.chatData);
// alert(this.state.chatData1);
// })
// .catch(error => {
// console.log(error);
// });
// });
this.setState({ loading_image: true }, () => {
mockApi().then(data => {
this.setState({
chatData1: data[0].id,
chatData: data,
loading_image: false
});
});
});
// end axios api call
this.setState(prevState => ({
activeIds: prevState.activeIds.find(user => user === id)
? prevState.activeIds
: [...prevState.activeIds, id]
}));
};
close = id => {
this.setState(prevState => ({
activeIds: prevState.activeIds.filter(user => user !== id)
}));
};
renderUser = id => {
const user = this.state.data.find(user => user.id === id);
if (!user) {
return null;
}
return (
<OpenedUser
chatData={this.state.chatData}
key={user.id}
data={user}
close={this.close}
/>
);
};
renderActiveUser = () => {
return (
<div style={{ position: "fixed", bottom: 0, right: 0 }}>
{this.state.activeIds.map(id => this.renderUser(id))}
</div>
);
};
render() {
return (
<div>
{this.state.data.map(person => (
<User key={person.id} data={person} open={this.open} />
))}
{this.state.activeIds.length !== 0 && this.renderActiveUser()}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
I see a few missing points in your code namely you are using li without ul which is a kind of invalid markup, then you have mapping for .username which is undefined field according to response which may also throw error.

Cannot mix a URL string with props in ReactJS

i am new on ReactJS and i am trying to find the correct way to mix a props of a parent component with a normal string URL
in my Child component i have two props in my child component:
this.props.originalUrl = https://server.com
this.props.todayDate = "2018-08-16"
and i have a url lets say it is
let url = https://server.com/123/2018-08-16/blabla
what i want is to make it dynamic url like
let url = `${this.props.originalUrl }/123/${this.props.todayDate }/blabla`
But when i use
let url = `${this.props.originalUrl }/123/2018-08-16/blabla`
The console give me the correct URL that i want
https://server.com/123/2018-08-16/blabla
but with two props like this
let url = `${this.props.originalUrl }/123/${this.props.todayDate}/blabla`
the console give me
https://server.com/123//blabla without the date
How can i mix them currently ??
Note: when i use {this.props.todayDate} in the Child componenet return it is look work and rendered as 2018-08-16
this is the full code
import React, { Component } from 'react';
import { extend } from 'underscore';
import { translate, Trans} from 'react-i18next';
import axios from 'axios';
import { Alert } from 'react-alert'
import TableNav from './tableNav';
import Table from './table';
class TableContainer extends Component {
constructor(props) {
super(props);
this.state = {
sortBy: 'id',
filteredData: [],
checkedboxArray: [],
sortingOptions: [
'id'],
sortingDirection: {
'id': true,
},
data: [],
itemsPerPage: 20,
totalPages: '',
firstUrl: '',
previousUrl: '',
currentUrl: '',
nextUrl: '',
lastUrl: '',
totalItems:'',
currentPageNumber: '',
originalurl: `${this.props.cmsUrl}performances?eq(flyers.id,empty())&gte(startDateTime,${this.props.todayDate})&sort(+startDateTime)`,
performancesSelected: [],
myItemsState: true
};
let url = this.state.originalurl;
axios.get(url, { withCredentials: true })
.then((response) => {
this.setState({
totalPages:response.data.pagination.pages,
totalItems:response.data.pagination.total,
currentPageNumber: response.data.pagination.page,
firstUrl:response.data.pagination.links.first,
previousUrl:response.data.pagination.links.previous,
currentUrl:response.data.pagination.links.current,
nextUrl:response.data.pagination.links.next,
lastUrl:response.data.pagination.links.last,
data:response.data.results,
});
});
this.getTotal = this.getTotal.bind(this);
this.onSelectChange = this.onSelectChange.bind(this);
this.onColumnClick = this.onColumnClick.bind(this);
this.filterData = this.filterData.bind(this);
this.sortData = this.sortData.bind(this);
this.checkedbox = this.checkedbox.bind(this);
this.nextPageFunc = this.nextPageFunc.bind(this);
this.previousPageFunc = this.previousPageFunc.bind(this);
this.firstpageFunc = this.firstpageFunc.bind(this);
this.lastpageFunc = this.lastpageFunc.bind(this);
}
getTotal() {
return this.state.data.length;
}
onSelectChange(e, option) {
if (option === 'sortBy') {
this.setState({ sortBy: e.target.value });
this.sortData(e.target.value, this.state.sortBy);
this.setState({ currentPage: 1});
} else {
this.setState({ itemsPerPage: e.target.value });
this.setState({ currentPage: 1});
}
}
onColumnClick(e) {
var clicked = e.target.getAttribute('class');
this.setState({ sortBy: clicked });
this.sortData(clicked, this.state.sortBy);
}
filterData() {
return this.state.data;
}
sortData(sortBy, previousSortBy) {
sortBy = sortBy.toLowerCase().replace(' ', '');
previousSortBy = previousSortBy.toLowerCase().replace(' ', '');
var ascending = this.state.sortingDirection[sortBy];
if (sortBy === previousSortBy) {
ascending = !ascending;
this.setState({ sortingDirection: extend(this.state.sortingDirection, { [sortBy]: ascending }) });
}
var data = this.state.data.sort(function(a, b) {
if(a[sortBy] < b[sortBy]) {
return ascending ? -1 : 1;
}
if(a[sortBy] > b[sortBy]) {
return ascending ? 1 : -1;
}
return 0;
});
this.setState({ data })
}
checkedbox(id){
let checkedboxArray = this.state.checkedboxArray;
let flyersAraay = this.state.data;
let performancesSelected = this.state.performancesSelected;
// if Selected ID are not in the checkedboxArray
if ( checkedboxArray.indexOf(id) === -1 ) {
checkedboxArray.push(id) ;
this.setState({checkedboxArray: checkedboxArray })
let selecObject = flyersAraay.find(function (xxx) { return xxx.id === id; });
performancesSelected.push(selecObject)
let data = JSON.stringify(performancesSelected)
sessionStorage.setItem( "Performances" , data)
}
// if Selected ID are in the checkedboxArray
else if ( checkedboxArray.indexOf(id) !== -1 ) {
let i = checkedboxArray.indexOf(id);
if (i !== -1) {
checkedboxArray.splice(i, 1);
performancesSelected.splice(i, 1);
this.setState({checkedboxArray: checkedboxArray })
let data = JSON.stringify(performancesSelected)
sessionStorage.setItem( "Performances" , data)
}
}
}
nextPageFunc() {
let StrUrl = JSON.stringify(this.state.nextUrl);
let smallUrl = StrUrl.split("external/").pop();
let editeUrl = this.props.cmsUrl + smallUrl;
let url = editeUrl;
axios.get(url, { withCredentials: true })
.then((response) => {
this.setState({
totalPages: response.data.pagination.pages,
totalItems: response.data.pagination.total,
currentPageNumber: response.data.pagination.page,
firstUrl: response.data.pagination.links.first,
previousUrl: response.data.pagination.links.previous,
currentUrl: response.data.pagination.links.current,
nextUrl: response.data.pagination.links.next,
lastUrl: response.data.pagination.links.last,
data: response.data.results,
});
});
}
previousPageFunc() {
let StrUrl = JSON.stringify(this.state.previousUrl);
let restUrl = StrUrl.split("external/").pop();
let editeUrl = this.props.cmsUrl + restUrl;
let url = editeUrl;
axios.get(url, { withCredentials: true })
.then((response) => {
this.setState({
totalPages: response.data.pagination.pages,
totalItems: response.data.pagination.total,
currentPageNumber: response.data.pagination.page,
firstUrl: response.data.pagination.links.first,
previousUrl: response.data.pagination.links.previous,
currentUrl: response.data.pagination.links.current,
nextUrl: response.data.pagination.links.next,
lastUrl: response.data.pagination.links.last,
data: response.data.results,
});
});
}
firstpageFunc() {
let StrUrl = JSON.stringify(this.state.firstUrl);
let restUrl = StrUrl.split("external/").pop();
let editeUrl = this.props.cmsUrl + restUrl;
let url = editeUrl;
axios.get(url, { withCredentials: true })
.then((response) => {
this.setState({
totalPages: response.data.pagination.pages,
totalItems: response.data.pagination.total,
currentPageNumber: response.data.pagination.page,
firstUrl: response.data.pagination.links.first,
previousUrl: response.data.pagination.links.previous,
currentUrl: response.data.pagination.links.current,
nextUrl: response.data.pagination.links.next,
lastUrl: response.data.pagination.links.last,
data: response.data.results,
});
});
}
lastpageFunc() {
let StrUrl = JSON.stringify(this.state.lastUrl);
let smallUrl = StrUrl.split("external/").pop();
let editeUrl = this.props.cmsUrl + smallUrl;
let url = editeUrl;
axios.get(url, { withCredentials: true })
.then((response) => {
this.setState({
totalPages: response.data.pagination.pages,
totalItems: response.data.pagination.total,
currentPageNumber: response.data.pagination.page,
firstUrl: response.data.pagination.links.first,
previousUrl: response.data.pagination.links.previous,
currentUrl: response.data.pagination.links.current,
nextUrl: response.data.pagination.links.next,
lastUrl: response.data.pagination.links.last,
data: response.data.results,
});
});
}
myItemsCheckbox(e) {
let state = this.state.myItemsState
if ( state === false ) {
axios.get( `${this.props.cmsUrl}performances?eq(flyers.id,empty())&gte(startDateTime,2018-08-16)&sort(+startDateTime)`, { withCredentials: true })
.then((response) => {
this.setState({
totalPages:response.data.pagination.pages,
totalItems:response.data.pagination.total,
currentPageNumber: response.data.pagination.page,
firstUrl:response.data.pagination.links.first,
previousUrl:response.data.pagination.links.previous,
currentUrl:response.data.pagination.links.current,
nextUrl:response.data.pagination.links.next,
lastUrl:response.data.pagination.links.last,
data:response.data.results,
});
});
this.setState({ myItemsState: true})
}
else if ( state === true ) {
axios.get( this.props.cmsUrl+"performances", { withCredentials: true })
.then((response) => {
this.setState({
totalPages:response.data.pagination.pages,
totalItems:response.data.pagination.total,
currentPageNumber: response.data.pagination.page,
firstUrl:response.data.pagination.links.first,
previousUrl:response.data.pagination.links.previous,
currentUrl:response.data.pagination.links.current,
nextUrl:response.data.pagination.links.next,
lastUrl:response.data.pagination.links.last,
data:response.data.results,
});
});
this.setState({ myItemsState: false })
}
}
render() {
const { itemsPerPage, totalPages, data, currentPageNumber, totalItems, firstUrl, previousUrl, currentUrl, nextUrl, lastUrl, checkedboxArray } = this.state;
return (
<div>
<div className="myItemsButton">
<Alert>{ alert => (
<span className="btn myItemsSpan ">
<input
className="inputSelect"
defaultChecked={this.state.myItemsState}
onChange={ () => { { alert.show('You have changed the Items order' )} ; this.myItemsCheckbox() } }
type="checkbox"
id="xd"
name="cc"
/>
<label htmlFor="xd"><span></span></label>
myItems
</span>
)}
</Alert>
</div>
<TableNav
itemsPerPage={itemsPerPage}
totalPages={totalPages}
data={data}
currentPageNumber={currentPageNumber}
totalItems={totalItems}
firstpageFunc={this.firstpageFunc}
previousPageFunc={this.previousPageFunc}
nextPageFunc={this.nextPageFunc}
lastpageFunc={this.lastpageFunc}
firstUrl={firstUrl}
previousUrl={previousUrl}
currentUrl={currentUrl}
nextUrl={nextUrl}
lastUrl={lastUrl} />
<Table
onColumnClick={this.onColumnClick}
checkedbox={this.checkedbox}
data={data}
checkedboxArray={checkedboxArray}
filteredData={this.filterData()} />
{ this.state.data.length === 0 && (
<table className="table noResultsTable bordered table-hover table-dark">
<tbody>
<tr>
<td>
<div className="col-12 text-center noResults">
{/* <i className="fas fa-cog"></i> */}
<i className="fa fa-exclamation-triangle"></i>
<span className="resultsText"><Trans>No results found</Trans> {this.props.todayDate} ...</span>
</div>
</td>
</tr>
</tbody>
</table>
)}
</div>
);
}
}
export default translate('translations')(TableContainer);
in the last <span className="resultsText">i can read the time as

Resources