this.state.data.map is not a function - reactjs

I'm making an API call with React and the Facebook Graph API
The API is working fine but the map method is showing
this.state.data.map is not a function
import React, { Component } from 'react';
import axios from 'axios';
class user extends Component {
constructor(props){
super(props);
this.state={
data:[123]
}
}
componentDidMount() {
axios.get("facebook url")
.then(response => {
if (response.status === 200 && response != null) {
this.setState({
data: response.data
});
} else {
console.log('problem');
}
})
.catch(error => {
console.log(error);
});
}
render(){
return (
<div>
{this.state.data.map((item,index) => {
return (
<div key={item.id}>
<h1>{item.message}</h1>
</div>
);
})}
</div>
);
}
}
export default user;

Related

How to fetch all the value in react

I am trying to fetch all the posts data from the admin site to show on my frontend but for now it is only print first value instead of all the data's.
I want solution on this, here is my code below.
import React, {Component} from 'react';
import { Link } from 'react-router-dom';
import { Stack } from './common/contentstack-api/api.js';
export default class App extends Component{
constructor() {
super()
this.state = { loading : true, result: null}
}
componentDidMount () {
var Query = Stack.ContentType("posts").Query()
.toJSON()
.find()
.then((result) => {
console.log(result);
this.setState({loading : false, result:result})
})
.catch((error) => {
console.log(error)
})
}
renderList (result) {
return (
<main>
<div className="media-body ">
{
this.state.result.map((value, index) => {
return (
<div className="article-metadata">
<ul>
<li>{ value[index].title}</li>
</ul>
</div>
)
})
}
</div>
</main>
)
}
render () {
const {loading, result} = this.state
return (this.state.loading) ? <h1>loading...</h1> : this.renderList(result[0])
}
}

React API data not showing up in JSX

[enter link description here][1]I am fetching API in react. I am able to see data in console but it is not appearing in JSX. I want to see Data id, name and value. But it is not appearing in browser.
[1]: https://codesandbox.io/s/late-thunder-456qp?file=/src/App.js
import React from 'react';
import axios from 'axios'
import './App.css';
class Main extends React.Component {
constructor(props) {
super(props)
this.state = {
users: [],
error: ''
}
}
componentDidMount(){
axios.get('https://jsonplaceholder.typicode.com/users')
.then( response => {
console.log(response);
this.setState({users: response.data})
})
.catch(error =>{
console.log(error);
})
}
render() {
const { users } = this.state
return (
<div>
<h2> Main Page</h2>
<p class="para-text"> Data from API</p>
{
users.length ?
users.map(post => <div key ={ users.id }> { users.name} </div>) : null
}
</div>
);
}
}
export default Main;
when mapping you named the key to your map as post and therefore when displaying them in jsx you must refer to that key
attached is a forked version of your sandbox https://codesandbox.io/s/late-thunder-456qp?file=/src/App.js
import "./styles.css";
import React from "react";
import axios from "axios";
class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
users: [],
error: ""
};
}
componentDidMount() {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then((response) => {
this.setState({ users: response.data });
})
.catch((error) => {
console.log(error);
});
}
render() {
const { users } = this.state;
return (
<div>
<h2> Main Page</h2>
<p class="para-text"> Data from API</p>
{users.length > 0
? users.map((post) => <div key={post.id}> {post.name} </div>)
: null}
</div>
);
}
}
export default Main;

React HOC with Router not finding page

Hi I am working on a react app with Routing and HOC. I expect to see a page but i get page not found when i know the page is there.
in componentDidMount this.setState, data is shown as undefined but in the HOC wrapper i see the data arrive from the server.
Before I wrapped the page in HOC i could see it rendering content so I know the content exists.
Here is my Page component which is being called via a Route :
import React, { Component } from "react";
import WithBackend from "./WithBackend";
class Page extends Component {
constructor(props) {
super(props);
this.state = { model: null };
}
render() {
if (this.state.model != null) {
return (
<div className="container">
<div className="row">
<div className="col-md">
<h1>{this.state.model.title}</h1>
</div>
</div>
</div>
);
} else {
return (
<div>
<h2>Home</h2>
</div>
);
}
}
componentDidMount() {
const data = this.props.getPage("1");
console.log(data);
this.setState({
model: data,
});
}
}
export default WithBackend(Page);
Here is the HOC component WithBackend: I am not sure if i should be setting the state on this class on in the class that is being wrapped.
When i debug the code in the getPage method, in the setState part i see the data being populated from the backend server.
import React from "react";
import ContentService from "./ContentService";
const WithBackend = (WrappedComponent) => {
class HOC extends React.Component {
constructor() {
super();
this.contentService = new ContentService();
this.getPage = this.getPage.bind(this); // <-- Add this
}
getPage(id) {
this.contentService
.getPage(id)
.then((response) => response.json())
.then((data) => {
this.setState({ model: data });
})
.catch((e) => {
console.log(e);
});
}
render() {
return <WrappedComponent getPage={this.getPage} {...this.props} />;
}
}
return HOC;
};
export default WithBackend;
and here is the contentService which only returns a promise:
class ContentService {
pageUrl = process.env.REACT_APP_BASE_URL + "/pages/";
getPage(id) {
const path = this.pageUrl + id;
const fetchPromise = fetch(path, {
method: "GET",
});
return Promise.resolve(fetchPromise);
}
}
export default ContentService;
Could anyone please advice what i am doing wrong?
Thanks in advance.
getPage is an asynchronous method, that should return a promise:
getPage(id) {
return this.contentService
.getPage(id)
.then((response) => response.json())
.catch((e) => {
console.log(e);
});
}
And then
componentDidMount() {
this.props.getPage("1").then(model => this.setState({ model }));
}

solve:Expected an assignment or function call and instead saw an expression no-unused-expressions

hey i am new in the field and want to display the state using the map and i am not able to do so
and there is no problem in the api call through axios so ignore it
my code is
import React, { Component } from 'react';
import axios from 'axios';
const url ='https://www.reddit.com/r/space.json';
class Apicall extends Component {
state={
posts:[],
subr:'space'
};
componentDidMount(){
this.getReddit();
}
getReddit=async()=>{
console.log('getredddit called sir ');
try {
let response=await axios.get(`https://www.reddit.com/r/${this.state.subr}.json`);
let posts=response.data.data.children.map(obj=>obj.data)
this.setState({posts:posts},()=>{console.log(this.state.posts);
})
} catch (error) {console.log(error);}}
render() {
let controlItems=this.state.posts.map(post=>{<h1 id={post.id}>{post.title}</h1>});
return (
<div>
<h1>{`/r/${this.state.subr}`} </h1>
{controlItems}
</div>);
}
}
export default Apicall;
You were iterating wrong on your data. response.data.data.children should be replaced with response.data.children. Implicit return of et controlItems=this.state.posts.map(post=>{{post.title}}); is also wrong.
import React from "react";
import "./styles.css";
export default function App() {
return (
<div className="App">
<Apicall />
</div>
);
}
class Apicall extends React.Component {
state = {
posts: [],
subr: "space"
};
componentDidMount() {
this.getReddit();
}
getReddit = async () => {
console.log("getredddit called sir ");
try {
let response = await fetch(
`https://www.reddit.com/r/${this.state.subr}.json`
);
response = await response.json();
console.log(response);
let posts = response.data.children.map(obj => obj.data);
this.setState({ posts: posts }, () => {
console.log(this.state.posts);
});
} catch (error) {
console.log(error);
}
};
render() {
let controlItems = this.state.posts.map(post => (
<h1 id={post.id}>{post.title}</h1>
));
return (
<div>
<h1>{`/r/${this.state.subr}`} </h1>
{controlItems}
</div>
);
}
}

How do i get data from the API(when i use map i get TypeError: userdata.map is not a function)

I need help to display the data from the API.
When i try to get the data with map i get an error. TypeError: userdata.map is not a function
import React from "react";
import axios from "axios";
export class HighscoreList extends React.Component {
constructor(props) {
super(props);
this.state = {
users: ""
};
}
componentDidMount() {
axios
.get("https://schnitzeljagdar.herokuapp.com/users/getAllUser")
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
}
render() {
return (
<React.Fragment>
<h2>User</h2>
{this.state.users}
</React.Fragment>
);
}
}
Try this https://codesandbox.io/s/wonderful-cherry-63ee9
export default class HighscoreList extends React.Component {
state = {
users: []
};
componentDidMount() {
axios
.get("https://schnitzeljagdar.herokuapp.com/users/getAllUser")
.then(res => this.setState({users:[res.data]}))
.catch(error => {
console.log(error);
});
}
render() {
const {users} = this.state;
let array = users[0]?Object.values(users[0]):[];
console.log(array)
return (
<React.Fragment>
{array.map((arr,index)=>
<div key={index}>
<h2>{arr.username}</h2>
<p>{arr.email}</p>
</div>
)}
</React.Fragment>
);
}
}

Resources