display data based on pass value id - reactjs

i want to display data based on its id. i have 2 page, app.js and display.js. in app.js i already display a table and clickable data to link to display.js. but i cant display data n display.js based on its id. i use API to get this all data and data in display.js is looping all data on result json and not only by id that i click on app.js.
can anyone helpme to pass the id from app.js to display.js and not loop data on display.js?
here's my code
App.js
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
errors: null,
isLoading: true
};
}
getData = async () => {
const option = {
url:api/url
method: 'POST',
headers: {
"Access-Control-Allow-Origin": "*"
},
data: {
"data": {
"data": "111111"
},
"encrypt": 0
}
};
axios(option)
.then(response => {
const tableData = response.data.data.map(post => {
const {id, name, type} = post;
return [
<Link to={'/display'}>{id}</Link>, //when i click this it link to display.js and in display.js only display data based on this id
<Link to={'/display'}>{name}</Link>,
<Link to={'/display'}>{type}</Link>
];
});
this.setState({
data: tableData,
isLoading: false
});
})
);
}
componentDidMount() {
this.getData();
}
render() {
const columns = ["ID", "Name", "Type"];
const options = {
filterType: "dropdown",
responsive: "scroll",
selectableRows:false
};
return (
<div>
<center><h3>Table</h3></center><br/>
{!isLoading ? (
<MUIDataTable
data={this.state.data}
columns={columns}
options={options}
/>)
: (
<p>Loading...</p>
)}
</div>
);
}
}
export default App
display.js
class App extends React.Component {
// State will apply to the posts object which is set to loading by default
constructor(props) {
super(props);
this.state = {
data: [],
isLoading: true,
errors: null
};
}
// Now we're going to make a request for data using axios
getData = async () => {
const option = {
url:api/url
method: 'POST',
headers: {
"Access-Control-Allow-Origin": "*"
},
data: {
"data": {
"data": "111111"
},
"encrypt": 0
}
};
axios(option)
.then(response => {
this.setState({
data: response.data.data,
isLoading: false,
});
console.log(response.data);
const data = JSON.parse(data);
})
);
}
componentDidMount() {
this.getData();
}
// Putting that data to use
render() {
const { isLoading, data} = this.state;
return (
<React.Fragment>
<h3>Data display</h3><br/>
<div>
{!isLoading ? (
data.map(post => {
const {id, name, age, type, gender} = post;
return (
//from API this data is looping and more than 1, i want to after click id from app.js it will link to this display.js page and only show data based on id
<div>
<Card>
<CardHeader color="info">
<h4 >Data </h4>
</CardHeader>
<CardBody>
<div><b>ID</b></div>
<div>{id}</div>
<div><b>Name</b>
<div>{name}</div>
<div><b>age</b></div>
<div>{age}</div>
<div><b>type</b></div>
<div >{type}</div>
<div><b>gender</b></div>
<div>{gender}</div>
</CardBody>
</Card>
<br/>
</div>
);
})
) : (
<p>Loading...</p>
)}
</div>
</React.Fragment>
);
}
}
export default App;
anyone can help to only show page display.js based on id i click in app.js?

You can pass the id within of the clicked row within the link child
<Link to={{
pathname: '/display',
state: {
data: post
}
}}></Link>
and in your display component you can get the id to send with the request
const { data } = this.props.location.data
and in your display component you'll get all the clicked row data and you can remove the loop from the render as well as the request

Related

Getting response on console but no result on page - React

I'm new to react and trying to fetch some data through an API. I got response on console but i'm unable to get any result on the page. This is my Index page:
const url = "https://chicken-coop.p.rapidapi.com/games/"
class PcComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
games: [],
}
}
GameSearch(term) {
const req = unirest("GET", "https://cors-anywhere.herokuapp.com/" + url + term);
req.query({
"platform": "pc",
"s": term
});
req.headers({
"x-rapidapi-host": "API Name"
"x-rapidapi-key": "API Key",
"useQueryString": true
});
req.end((res) => {
if (res.error) throw new Error(res.error);
const games = res.body.Search;
this.setState({ games: games}, () =>{ console.log(this.state)});
console.log(res.body);
});
}
render() {
const GameSearch = _.debounce((term) => {this.GameSearch(term)},300)
return (
<div>
<Search onSearchTermChange = {GameSearch} />
{
this.state.games && this.state.games.map((game) => {
return <Game {...game}/>
})
}
</div>
)
}
}
And My Code to Display the received data
class Game extends Component {
render() {
const {title, description, image} = this.props;
return (
<div className="game">
<div className="title-description">
<h1 className="title">{title}</h1>
<h2 className="description">{description}</h2>
</div>
<div className="image">
<img src={image} alt="My Game Poster" />
</div>
</div>
)
}
}
I noticed that initially the state is '[]' as i defined but after the setState it gets undefined.
I attached the response i'm getting from the API. Please help me fix this :D

How to add page number to the URL

Could someone please tell me how can I add page number to my url. The component is as follows:
/** NPM Packages */
import React, { Component } from "react";
import { connect } from "react-redux";
import { Spinner, Pagination } from "react-bootstrap";
//import styles from "./App.module.css";
/** Custom Packages */
import List from "../List";
//import fetchCategories from "../../../actions/configuration/category/fetchCategories";
import deleteCategory from "../../../actions/configuration/category/deleteCategory";
import API from "../../../../app/pages/utils/api";
class Category extends Component {
constructor(props) {
super(props);
this.state = {
mesg: "",
mesgType: "",
isLoading: true,
total: null,
per_page: null,
current_page: 1,
pdata: []
};
this.fetchCategoriesAPI = this.fetchCategoriesAPI.bind(this);
}
fetchCategoriesAPI = async pno => {
await API.get("categories?offset=" + (pno.index+1))
.then(res => this.setState({ pdata: res.data }))
.then(() => this.props.passToRedux(this.state.pdata))
.catch(err => console.log(err));
};
componentDidMount = async () => {
const { state } = this.props.location;
if (state && state.mesg) {
this.setState({
mesg: this.props.location.state.mesg,
mesgType: this.props.location.state.mesgType
});
const stateCopy = { ...state };
delete stateCopy.mesg;
this.props.history.replace({ state: stateCopy });
}
this.closeMesg();
await this.fetchCategoriesAPI(1);
this.setState({ isLoading: false });
};
onDelete = async id => {
this.props.removeCategory(id);
await deleteCategory(id).then(data =>
this.setState({ mesg: data.msg, mesgType: "success" })
);
this.closeMesg();
};
closeMesg = () =>
setTimeout(
function() {
this.setState({ mesg: "", mesgType: "" });
}.bind(this),
10000
);
/** Rendering the Template */
render() {
let activePage = this.state.pdata.currPage;
let items = [];
let totalPages = Math.ceil(this.state.pdata.totalCount / 10);
for (let number = 1; number <= totalPages; number++) {
items.push(
<Pagination.Item key={number} active={number == activePage}>
{number}
</Pagination.Item>
);
}
const paginationBasic = (
<div>
<Pagination>
{items.map((item,index)=>{
return <p key={index} onClick={() => this.fetchCategoriesAPI({index})}>{item}</p>
})}
</Pagination>
<br />
</div>
);
const { mesg, mesgType, isLoading } = this.state;
return (
<>
{mesg ? (
<div
className={"alert alert-" + mesgType + " text-white mb-3"}
role="alert"
>
{mesg}
</div>
) : (
""
)}
{isLoading ? (
<div className="container-fluid">
<h4
className="panel-body"
style={{ "text-align": "center", margin: "auto" }}
>
Loading
<Spinner animation="border" role="status" />
</h4>
</div>
) : (
<div>
<List
listData={this.props.categories}
listName="category"
_handleDelete={this.onDelete.bind(this)}
/>
{paginationBasic}
</div>
)}
</>
);
}
}
const matchStatestoProps = state => {
return { categories: state.categories };
};
const dispatchStatestoProps = dispatch => {
return {
passToRedux: pload =>
dispatch({ type: "FETCH_CATEGORIES", payload: pload }),
removeCategory: id => dispatch({ type: "DELETE_CATEGORY", payload: id })
};
};
export default connect(matchStatestoProps, dispatchStatestoProps)(Category);
the route is as follows:
<Route exact path="/categories/:page?" component={Category} />
So basically I want the page number to be displayed in the URL. Also if I change the page number, the data should load the corresponding page. Please help me
Could someone please help me out?
In a class component:
Your router will pass match in as a prop. When your component mounts, get this.props.match.params.page and load the data accordingly:
class MyComponent extends React.Component {
componentDidMount () {
// get the 'page' param out of the router props.
// default to 0 if not specified.
const { page = 0 } = this.props.match.params;
// it comes in as a string, parse to int
const p = parseInt(page, 10);
// do whatever you need to do (load data, etc.)
}
}
In a function component:
In a function component, you can get the page param via react-router's useParams hook:
import { useParams } from 'react-router-dom';
function MyComponent () {
const { page } = useParams(); // get the 'page' router param
const p = parseInt(page, 10); // comes in as a string, convert to int
// do whatever you need to do with it
}
If you need prev/next navigation you can deduce those page numbers from the current page.
I made this quick example that demonstrates how to access and use the route's url parameters via react router's useParams hook and how to do it via the match prop with a class component.
You can get page number from props like this:
const matchStatestoProps = (state, ownProps) => {
return { id: ownProps.match.params.id; categories: state.categories };
};
In your routes:
<Route path="/page/:id" component={Page} />

How to make React.js fetch data from api as state and pass this state data from its parent to child component

I am working on a React.js + D3.js project. I wanted App.js to fetch data from a json file and save this data into state and pass this parent sate data down to my child component state through the property. I found if I use static data in App.js works fine, but once fetching from a json file, it failed because no data can be stored into property. My App.js like this:
import React, { Component } from 'react';
import SandkeyGraph from './particle/SandkeyGraph';
class App extends Component {
state = {
data : null
}
// works fine in this way!
// state = {
// data: {
// "nodes":[
// {"node":0,"name":"node0"},
// {"node":1,"name":"node1"},
// {"node":2,"name":"node2"},
// {"node":3,"name":"node3"},
// {"node":4,"name":"node4"}
// ],
// "links":[
// {"source":0,"target":2,"value":2},
// {"source":1,"target":2,"value":2},
// {"source":1,"target":3,"value":2},
// {"source":0,"target":4,"value":2},
// {"source":2,"target":3,"value":2},
// {"source":2,"target":4,"value":2},
// {"source":3,"target":4,"value":4}
// ]}
// }
componentWillMount() {
this.getData('./data/sankey.json');
}
getData = (uri) => {
fetch(uri)
.then((response) => {
return response.json();
})
.then((data) => {
// successful got the data
console.log(data);
this.setState({ data });
});
}
render() {
// failed
const { data } = this.state;
return (
<div>
<SandkeyGraph
height={300}
width={700}
id="d3-sankey"
sankeyData = {this.state.data}
/>
</div>
);
}
}
export default App;
parrt of my is like this:
class SankeyGraph extends Component {
displayName: 'SankeyGraph';
state = {
sankeyData : null
}
constructor(props) {
super(props);
this.state.sankeyData = props.sankeyData || null;
}
PropTypes : {
id : PropTypes.string,
height: PropTypes.number,
width: PropTypes.number,
sankeyData : PropTypes.object,
}
componentDidMount () {
// will be null, if using fetch from App.js
//console.log(this.state.sankeyData);
this.setContext();
}
//...
Does anyone know how to handle this situation? Thank you so much in advanced!
After working out the problem, it turned out that there was no problem with fetch. It just didn't account for null in any of the components in the program (It would crash after using a null value.
For example in render:
render() {
if (this.state.data) {
return (
<div>
<SandkeyGraph
height={300}
width={700}
id="d3-sankey"
sankeyData = {this.state.data}
/>
</div>
);
}
else {
return <div/>
}
}
Or, the use of a ternary operator would work as well to be more concise (answer by #Eliran):
return (
{this.state.data ?
<div>
<SandkeyGraph
height={300}
width={700}
id="d3-sankey"
sankeyData = {this.state.data}
/>
</div> : <div>No Data Available</div>
);
You can add in your render function a condition:
render() {
// failed
const { data } = this.state;
return (
<div>
{data ?
<SandkeyGraph
height={300}
width={700}
id="d3-sankey"
sankeyData={data}
/> : "Loading..."
}
</div>
);
}
and only if data is populated the component will be rendered.
...
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
data : null
}
}
It seems like an error on the state declaration?
1.- Import your json in App component on top like this: import jsonData from './data/sankey.json'
2.- Set jsonData in state jsonData in App component.
constructor(props) {
super(props)
this.state = {
jsonData : {}
}
}
componentWillMount() {
this.setState({ jsonData })
}
You do not need to fetch as you have your json locally.
Once you have your json in your state, you can display it in render like this for example:
this.state.jsonData.data.links.map(x=>
<div>
<div>x.links.source</div>
<div>x.links.target</div>
</div>
)
I've been testing and you need to replace the getData() method to this:
getData = (uri) => {
fetch(uri, {
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then((response) => {
return response.json();
})
.then((data) => {
// successful got the data
console.log(data);
this.setState({ data });
});
}
This is because you need to declare 'Content-Type' and 'Accept' headers on your fetch options in order to make your request.

Update Apollo store after filtered query

I have a list of items which can be filtered out using certain criteria. Whenever i perform a search, i want to grab a filtered item and update its content which seems to update the apollo store correctly, but for some reason changes are not being shown. Perhaps the componentWillReceiveProps lifecycle method is not being fired and i need to implement it by myself?
I tried updating the store manually using "update" after the mutation but it wont work also.
This is my code so far:
ClientList.js
class ClientList extends Component {
constructor(props) {
super(props);
this.state = {
hasMoreItems: true,
loading: false,
clients: [],
searchText: ''
}
}
_executeSearch = async () => {
const { searchText } = this.state;
this.setState({ loading: true });
const result = await this.props.client.query({
query: ALL_CLIENTS_QUERY,
variables: { searchText },
fetchPolicy: 'network-only'
})
this.setState({
clients: result.data.allClients,
loading: false
});
}
render() {
let { allClients, loading, fetchMore } = this.props.data;
const { hasMoreItems, clients, searchText } = this.state;
if (clients.length > 0) {
allClients = clients;
loading = this.state.loading;
}
return (
<section>
<h1 className="text-center">Clients</h1>
<InputGroup>
<InputGroupButton>
<Button onClick={() => this._executeSearch()}>I'm a button</Button>
</InputGroupButton>
<Input
onChange={(e) => this.setState({ searchText: e.target.value })}
placeholder="Search by social or comercial name"
/>
</InputGroup>
{loading ?
<div className="text-center mt-4">
<i className="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i>
</div>
: <div className="mt-3">
{allClients.map(client =>
<div key={`client-${client.id}`} className="client-content">
<Link to={`/clients/${client.id}`}>
<h1 className="mb-1">
{client.socialName}
<small className="text-muted ml-3">{client.comercialName}</small>
</h1>
</Link>
</div>
})
</div>
</section>
);
};
}
export default withApollo(graphql(ALL_CLIENTS_QUERY)(ClientList));
ClientEdit.js
class ClientEdit extends Component {
onSubmit = async (e) => {
e.preventDefault();
this.setState({ loading: true });
const payload = {
id: this.props.match.params.id,
rfc: this.state.rfc,
socialName: this.state.socialName,
legalRepresentative: this.state.legalRepresentative,
comercialName: this.state.comercialName
}
// Mutation updates the store but doesnt show results
const resp = await this.props.mutate({
variables: payload,
update: (store, { data: { updateClient } }) => {
// Tried updating but it doesnt show changes also;
}
});
}
}
export default compose(
graphql(GET_CLIENT_QUERY, {
options: props => ({
variables: {
id: props.match.params.id
}
})
}),
graphql(UPDATE_CLIENT_MUTATION)
)(ClientEdit);
better if we check that the data is ready and we can render it out , and when data still fetching so no render associated with that apollo data object should be done:
render(){
const {loading} = this.props.data;
if(loading) {return <div>Loading...</div>}
return (
...
)
I manage to fix this using the componentWillReceiveProps lifecycle method. I dont know if this is a bug or maybe there is another solution;
componentWillReceiveProps(newProps) {
const { allClients, loading } = newProps.data;
if (!loading) {
const clients = _.intersectionBy(allClients, this.state.clients, 'id');
this.setState({ clients });
}
}

reactjs - moving list items back and forth between two components

I have a small exercise I'm working on to learn ReactJS. I'm making an API call to display a list from iTunes, and when the individual list items are clicked on, they move over to a new list (kind of like a queue). When clicked on in the new list, they move back to the original list, however the list item is not being removed from the new list when it gets moved back. Here is a jsfiddle of my problem: https://jsfiddle.net/6k9ncbr6/
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
searchResults: [],
moveResults: []
}
this.handleEvent = this.handleEvent.bind(this);
}
showResults = (response) => {
this.setState({
searchResults: response.results,
moveResults: []
})
}
search = (URL) => {
$.ajax({
type: 'GET',
dataType: 'json',
url: URL,
success: function(response) {
this.showResults(response);
}.bind(this)
});
}
handleEvent = (clickedTrack) => {
const { searchResults, moveResults } = this.state;
const isInSearchResults = searchResults.some(result => result.trackId === clickedTrack.trackId);
this.setState({
searchResults: isInSearchResults ? searchResults.filter(i => i.trackId !== clickedTrack.trackId) : [...searchResults, clickedTrack],
moveResults: isInSearchResults ? [...moveResults, clickedTrack] : moveResults.filter(i => i.trackId !== clickedTrack)
});
}
componentDidMount() {
this.search('https://itunes.apple.com/search?term=broods');
}
render(){
return (
<div>
<Results
searchResults={this.state.searchResults}
handleEvent={this.handleEvent}/>
<Results
searchResults={this.state.moveResults}
handleEvent={this.handleEvent} />
</div>
);
}
}
class Results extends React.Component {
render(){
const { handleEvent, searchResults } = this.props;
return(
<ul>
{this.props.searchResults.map((result, idx) =>
<ResultItem
key={`${result.trackId}-${idx}`}
trackName={result.trackName}
track={result}
handleClick={handleEvent} />
)}
</ul>
);
}
}
class ResultItem extends React.Component {
render(){
const { handleClick, track, trackName } = this.props
return <li onClick={() => handleClick(track)}> {trackName} </li>;
}
}
ReactDOM.render(
<App />, document.getElementById('root')
);
You left off a property name:
moveResults: isInSearchResults ? [...moveResults, clickedTrack] : moveResults.filter(i => i.trackId !== clickedTrack.trackId)
The clickedTrack.trackId is missing the .trackId in your existing code.
Here's the working jsFiddle.

Resources