Display pagination Wordpress rest api with ReactJS - reactjs

I have problem with displaying pagination. I'm using Wordpress REST API to fetch my posts
Here is my code:
import React, { Component } from "react";
import "./App.css";
class App extends React.Component {
constructor() {
super();
this.state = {
items: [],
totalPages: '',
nextPage: '',
};
this._loadData = this._loadData.bind(this);
}
componentDidMount() {
const url = 'http://localhost/wp-json/wp/v2/';
this._loadData(url);
}
_loadData(url) {
request.get(url).then((response) => {
this.setState({
items: response.body.items.data,
totalPages: response.body.items.last_page,
nextPage: response.body.items.next_page_url
});
});
}
render() {
let items = _.map(this.state.items, (item) => {
return (
<div key={item.id}>
<div className="content">
<span>
{item.type}
</span>
</div>
</div>
)
});
return (
<div>
{items}
</div>
<div>
<a href="#0" onClick={this._loadData(this.state.nextPage)}/>Next
</div>
}
}
export default App;
I need help beacuse I can not figure out where the problem is. I would appreciate some tutorial or something like that.

Your WordPress's REST API Endpoint isn't correct.
When you fetching data from http://localhost/wp-json/wp/v2/ using GET method, it will returns only the namespaces and routes.
If you would like to pull posts or pages, should use path like this.
http://localhost/wp-json/wp/v2/{post_type}
Replace {post_type} with the post type in plural word.
For example you would like to get latest posts you should request to
http://localhost/wp-json/wp/v2/posts
Also you can preview this url in your browser.

Related

How to mapping restful api in react app via bootstrap

I want to consume restful api in react application via bootstrap. But I can't mapping correctly. I believe that the problem is brackets. But I couldn't figure out. (ignore my div part if I can mapping, I will update that part.)
My restful api: https://api.coindesk.com/v1/bpi/currentprice.json
Restful api Json formatted:
{
"time":{
"updated":"Jun 2, 2022 08:38:00 UTC",
"updatedISO":"2022-06-02T08:38:00+00:00",
"updateduk":"Jun 2, 2022 at 09:38 BST"
},
"disclaimer":"This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
"chartName":"Bitcoin",
"bpi":{
"USD":{
"code":"USD",
"symbol":"$",
"rate":"29,941.3155",
"description":"United States Dollar",
"rate_float":29941.3155
},
"GBP":{
"code":"GBP",
"symbol":"£",
"rate":"23,980.6882",
"description":"British Pound Sterling",
"rate_float":23980.6882
},
"EUR":{
"code":"EUR",
"symbol":"€",
"rate":"28,094.2357",
"description":"Euro",
"rate_float":28094.2357
}
}
}
My App.js
import React, {Component} from 'react';
import Lists from './example/lists';
class App extends Component {
render() {
return (
<Lists lists={this.state.lists} />
)
}
state = {
lists: {}
};
componentDidMount() {
fetch('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(res => res.json())
.then((data) => {
this.setState({ lists: data })
})
.catch(console.log)
}
}
export default App;
My list.js:
import React from 'react'
const Lists = ({lists}) => {
return (
<div>
<center><h1>Exchange</h1></center>
{lists.map((list) => (
<div class="card">
<div class="card-body">
<h5 class="card-title">{list.time}</h5>
<h5 class="card-title">{list.bpi}</h5>
</div>
</div>
))}
</div>
)
};
export default Lists
The json is not an array therefore no you do not need to map through it. Remove the map from the List component.
import React from 'react'
const Lists = ({lists}) => {
return (
<div>
<center><h1>Exchange</h1></center>
<div class="card">
<div class="card-body">
<h5 class="card-title">{lists.time}</h5>
<h5 class="card-title">{lists.bpi}</h5>
</div>
</div>
</div>
)
};
export default Lists
I am not sure your json is complete but, since your json is returning an object, you cannot use map or any loop. You just need to display the data without looping

Uncaught Error: Objects are not valid as a React child (found: object with keys {message})

I have ReactJS application which receives data from SpringBoot API. I am successfully able to receive the data from SpringBoot as seen through console.log().
But i am getting error while displaying result from springboot to a page.
Error is in WelcomeComponent: .then(response =>this.handleSuccessFullResponse(response)) is causing whole page to go blank.
import React, { Component } from "react";
import { Link } from "react-router-dom";
import HelloWorldService from "../../API/todo/HelloWorldService";
class WelcomeComponent extends Component {
constructor(props) {
super(props)
this.getWelcomeMessage = this.getWelcomeMessage.bind(this)
this.state = {
welcomeMessage: ' '
}
this.handleSuccessFullResponse = this.handleSuccessFullResponse.bind(this)
}
render() {
return (
<>
<h1>Welcome!</h1>
<div className="container">
Welcome {this.props.params.name} You can manage your tods from{" "}
<Link to="/todos">here</Link>
</div>
<div className="container">
Click here to get customized message.
<button onClick={this.getWelcomeMessage} className="btn btn-success">
Here
</button>
</div>
<div className="container">
{this.state.welcomeMessage}
</div>
</>
);
}
getWelcomeMessage() {
//console.log("getMessageClicked");
HelloWorldService.executeHelloWorldService()
.then(response =>this.handleSuccessFullResponse(response)) //request successful
//.then(response=>console.log(response.data))
//.catch(); //request failed
}
handleSuccessFullResponse(response) {
this.setState({welcomeMessage: response.data})
}
}
export default WelcomeComponent;
you are getting Object in the response which is this:
{message: Hello World}
In order to render it, you do not need Object but the value .
You are doing this:
handleSuccessFullResponse(response) {
this.setState({welcomeMessage: response.data})
}
Replace it to this:
handleSuccessFullResponse(response) {
this.setState({welcomeMessage: response.data.message})
}
Hope this helps, if error occurs, share the snapshot with details here.
Regards,
Shameel Uddin

React Component crashes on reload

I have a notes-list component that gets the notes data as props from the main component.
Inside the notes-listcomponent, there is a notes-item component which has a dynamic route that loads notesItem-page. So, for every notes-item there is a dynamic url for it's respective notesItem-pagewhich has all the details about the notesItem object. I use Link from react-router-dom
The notes-list component looks like this:
export class NotesList extends Component {
constructor(props) {
super(props);
}
render() {
const { isLoggedIn } = this.props.loggedInContext;
return (
<div className="notes-list">
{this.props.notes.map((notesItem) => (
<Link
to={{
pathname: `${notesItem.slug}`,
id: notesItem._id,
}}
style={{
textDecoration: "none",
color: "#fea82f",
}}
>
<NotesItem notes={notesItem} />
</Link>
))}
</div>
);
}
}
export default loggedInContext(NotesList);
This successfully redirects me to the NotesItem-page with the correct props and inside the notesItem-page I get the receive the id of the object that I had passed as props and make an API call with that particular id in ComponentDidMount() method.
This works perfectly. However, it crashes on reload. It gives the following error:
I am guessing it is because of ComponentDidMount works only once,but I do not seem to find an alternate solution to this problem.
The notesItem-page component looks like this:
export class notesItemPage extends Component {
constructor(props) {
super(props);
this.state = {
notesItem: [],
};
}
componentDidMount() {
fetch(`http://localhost:5000/api/v1/notes/fetch/${this.props.location.id}`)
.then((notesItem) => notesItem.json())
.then((notesItem) =>
this.setState({ notesItem: notesItem.data, isLoaded: true })
);
}
render() {
const { notesItem } = this.state;
return (
<div className="notesItem-details">
<h1> {notesItem.title} Notes</h1>
</div>
);
}
}
export default notesItemPage;
It would be great if anyone could help me with this, thanks!
Issue is here:
<h1> {notesItem.title} Notes</h1>
here the notesItem is coming from an axios call and this data is not available on the time of first component render and this is causing the issue ( app crash ).
So change this:
<h1> {notesItem.title} Notes</h1>
to
<h1> { notesItem && notesItem.title } Notes</h1> // use it when it is available from axios call

Send Array from API Response to Components

I'm trying to capture wepb url from an axios response and pass it to an image component.
I want to loop through data and show every data[all].images.original.webp
I've tried .map() with no success
I think some of my problems involve waiting on the response to finish, and UserItem is probably all wrong
Here is the console.log I get during troubleshooting.
App
import React, { Component } from "react";
import axios from "axios";
import Users from "./components/Users";
class App extends Component {
state = {
users: [] /* Set users inital state to null */,
loading: false
};
async componentDidMount() {
this.setState({ loading: true });
const res = await axios.get(
"http://api.giphy.com/v1/stickers/search?q=monster&api_key=sIycZNSdH7EiFZYhtXEYRLbCcVmUxm1O"
);
/* Trigger re-render. The users data will now be present in
component state and accessible for use/rendering */
this.setState({ users: res.data, loading: false });
}
render() {
return (
<div className="App">
<Users loading={this.state.loading} users={this.state.users} />
{console.log(this.state.users)}
</div>
</div>
);
}
}
export default App;
Users Component
import React, { Component } from "react";
import UserItem from "./UserItem";
export default class Users extends Component {
render() {
return (
<div className="ui relaxed three column grid">
{this.props.users.map(data => (
<UserItem key={data.id} gif={data.images.original.webp} />
))}
</div>
);
}
}
UserItem
import React from "react";
import PropTypes from "prop-types";
const UserItem = ({ user: { gif } }) => {
return (
<div className="column">
<img src={gif} className="ui image" />
</div>
);
};
UserItem.propTypes = {
user: PropTypes.object.isRequired
};
export default UserItem;
Error Message
So it took me a while to read up on the giphy api, but it turns out you might possibly be using the wrong protocol, http instead of https, so the axios call was actually throwing an error and that was getting saved in state since your code doesn't handle it, i.e. state.users wasn't an array to map over.
axios.get("https://api.giphy.com/v1/stickers/search?q=monster&api_key=sIycZNSdH7EiFZYhtXEYRLbCcVmUxm1O")
The response data is also response.data.data, and your UserItem component just receives gif as a prop, not the user object. I've coded up a working sandbox.
Render the output in a conditional expression so that it does not try to render the .map() before the array of data is available. Likely that this.props.users is undefined the first time the component tries to render and so you get a fatal TypeError.
{this.props.users && this.props.users.map(data => (
<UserItem key={data.id} gif={data.images.original.webp} />
))}
The && expression acts as a boolean conditional when used like this. Now the first time the component tries to render and this.props.users is undefined it will not try and run the .map(), when the props update and the array is available it will render.

Data response not able to map in react js app

I'm new to react and trying to create a eCommerce website. For that I have used a url endpoint to map the data.
http://149.129.128.3:3737/search/resources/store/1/categoryview/#top?depthAndLimit=-1,-1,-1,-1
Well, the second level of subcategories, I'm able to implement successfully, but for the third level of category, I'm not able to render perfectly
I'm sending the screenshot of the json response.
And this is what I have implemented till now, the screen shot.
As you can see, from the screenshot, I'm able to implement the top navigation category and even under it. But there is one more sub level of category-- e.g: under girls section, there are more sub categories which I'm unable to implement.
My code for the same:
topNavigation.js
import React, { Component } from 'react';
import axios from 'axios';
import SubMenu from './subMenu';
class Navigation extends Component {
state = {
mainCategory: []
}
componentDidMount() {
axios.get('http://localhost:3030/topCategory')
.then(res => {
console.log(res.data.express);
this.setState({
mainCategory: res.data.express.catalogGroupView
})
})
}
render() {
const { mainCategory } = this.state;
return mainCategory.map(navList => {
return (
<ul className="header">
<li key={navList.uniqueID}>
<a className="dropbtn ">
{navList.name}
<ul className="dropdown-content">
<SubMenu below={navList.catalogGroupView}/>
</ul>
</a>
</li>
</ul>
)
})
}
}
export default Navigation;
subMenu.js
import React, { Component } from 'react';
import SubListMenu from './subListMenu';
class SubMenu extends Component {
render() {
const {below} = this.props;
return below.map(sub => {
return (
<li key={sub.uniqueID}>
<a>
{sub.name}
<ul>
<SubListMenu subBelow={this.props.below}/>
</ul>
</a>
</li>
)
})
}
}
export default SubMenu;
subListMenu.js
import React, { Component } from 'react';
class SubListMenu extends Component {
render() {
const {subBelow} = this.props;
console.log(subBelow)
return subBelow.map(subl => {
return (
<li key={subl.uniqueID}> <a>{subl.name}</a></li>
)
})
}
}
export default SubListMenu;
Can anyone help me in resolving this issue. I don't know where I'm getting it wrong. I would grateful if someone could guide me on this.
You need is the recursive call to the component. So for example, for the third level you can again call the SubMenu something like this. this will again call the Submenu component and bind your third level (not just third 4,5... etc).
Note: I have not tested this code.
return subBelow.map(subl => {
return (
<React.Fragment>
<li key={subl.uniqueID}> <a>{subl.name}</a></li>
{subl.catalogGroupView !== undefined && <SubMenu below={subl.catalogGroupView} />}
</React.Fragment>
)
});

Resources