After fetch state returns undefined - javascript

Im using fetch to post data to my local api, but when trying to get them and error like this occures. In fetch i get result perfectly fine, but after that trying to pass that into state like below:
this.setState({
items: result.items })
but items returns undefined and don't know why ?
My code:
class App extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
error: null,
isLoaded: false
};
this.setState = this.setState.bind(this);
}
componentDidMount() {
fetch("http://localhost:3000/items")
.then(res => res.json())
.then(result => {
console.log(result);
this.setState({
items: result.items,
isLoaded: true
});
console.log(this.state.items)
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
<h1>Saved items:</h1>
{
items && items.map(item => (
<li key={item.name}>
item: {item.name} {item.price}
</li>
))
}
</ul>
);
}
}
}

You can do either:
this.setState({
items: result.items || [],
isLoaded: true
});
or
{
items && items.map(item => (
<li key={item.name}>
{item.name} {item.price}
</li>
))
}

Related

Sort data by title in React

how can i sort my data by title? This is my code:
And how can i call this 3 calls at the same time? I tried with "Promise All" but didn't work for me..
Thanks for help! ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
import './Style.css';
class PostList extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
data: [],
items: []
};
}
componentDidMount() {
fetch(this.props.url)
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
data: result.data,
items: result.items
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { error, isLoaded, data } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Please wait...</div>;
} else {
return (
<div> <table style={{ width: '100%'}}>
{data.items.map(item => (
<div>
<tr>
<th>Title:</th> <td>{item.title}</td>
</tr>
<tr>
<th>Artist:</th> <td>{item.artist}</td>
</tr>
<tr>
<th>Label:</th> <td>{item.label}</td>
</tr>
<tr>
<th>Year:</th> <td>{item.year}</td>
</tr>
</div>
))}
</table>
</div>
);
}
}
}
export default PostList
AND
import React, {Component} from 'react';
import PostList from './PostList';
class index extends Component {
render () {
return (
<div style={{
display: 'inline-flex'
}}>
<PostList url={"https://api.netbet.com/development/randomFeed?website=casino&lang=eu&device=desktop&source=list1"} />
<PostList url={"https://api.netbet.com/development/randomFeed?website=casino&lang=eu&device=desktop&source=list2"} />
<PostList url={"https://api.netbet.com/development/randomFeed?website=casino&lang=eu&device=desktop&source=list3"} />
</div>
)
}
}
export default index;
To sort the items just use Array.prototype.sort and String.prototype.localeCompare to compare the titles:
const sortedItems = data.items.sort((item1, item2) => item1.title.localeCompare(item2.title));
// and then render sorted items
{sortedItems.map(item => (...)}
If you want to do three calls at the same time you really need to use Promise.all. It can be done in parent component, or inside of PostList. So you can do the following:
const LIST_URLS = [
'https://api.netbet.com/development/randomFeed?website=casino&lang=eu&device=desktop&source=list1',
'https://api.netbet.com/development/randomFeed?website=casino&lang=eu&device=desktop&source=list2',
'https://api.netbet.com/development/randomFeed?website=casino&lang=eu&device=desktop&source=list3'
];
...
async componentDidMount() {
this.setState({ isLoading: true });
try {
const lists = await Promise.all(LIST_URLS.map((url) => {
return fetch(this.props.url).then(res => res.json());
});
const list = lists.flat();
const sortedList = data.items.sort((item1, item2) => item1.title.localeCompare(item2.title));
this.setState({ list: sortedList });
} catch (error) {
this.setState({ error });
} finally {
this.setState({ isLoading: false });
}
}
render() {
// here you can just render single list with all the items, passing them as a prop
const { isLoading, error, items } = this.state;
return (
<div>
{isLoading && 'Loading...'}
{items && <PostList list={this.state.list} />}
{error && 'Failed to fetch'}
</div>
);
}
If all 3 API data should be sorted, then you have to use like below. If you want individual API responses to be sorted use sort before updating the state.
class PostList extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
data: [],
items: [],
};
this.callAPi = this.callAPi.bind(this);
}
callAPi(url) {
return fetch(url)
.then((res) => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
data: [...result.data].sort((item1, item2) =>
item1.title.localeCompare(item2.title)
),
items: [...result.items].sort((item1, item2) =>
item1.title.localeCompare(item2.title)
),
});
},
(error) => {
this.setState({
isLoaded: true,
error,
});
}
);
}
componentDidMount() {
Promise.all(props.urls.map(this.callAPi));
}
render() {
const { error, isLoaded, data } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Please wait...</div>;
} else {
return (
<div>
<table style={{ width: "100%" }}>
{data.items.map((item) => (
<div>
<tr>
<th>Title:</th> <td>{item.title}</td>
</tr>
<tr>
<th>Artist:</th> <td>{item.artist}</td>
</tr>
<tr>
<th>Label:</th> <td>{item.label}</td>
</tr>
<tr>
<th>Year:</th> <td>{item.year}</td>
</tr>
</div>
))}
</table>
</div>
);
}
}
}
USE
<PostList
urls={[
"https://api.netbet.com/development/randomFeed?website=casino&lang=eu&device=desktop&source=list1",
"https://api.netbet.com/development/randomFeed?website=casino&lang=eu&device=desktop&source=list2",
"https://api.netbet.com/development/randomFeed?website=casino&lang=eu&device=desktop&source=list3",
]}
/>;

Infinity fetching loop

Once I am opening my DocumentViewer fetching does infinity loop and I cannot see why this is happening, could somebody maybe see where is the problem, Its something to do with state and props but i cannot figure out why, it would be amazing to know what is the problem and how to approach it
class GeneralDocPresenter extends React.Component {
state = {
metaInfoDocs: [],
docs: [],
loading: false
};
updateDoc = () => {
this.props.selectedDocsStore.clear();
this.props.selectedDocsStore.setViewDocId(0);
this.setState({ loading: true });
this.props
.fetchMetaDocs()
.then((r) => this.setState({ metaInfoDocs: r.data, loading: false }))
.catch((err) => {
this.setState({ loading: false });
errorWithMessage("Could not load documents");
});
this.props.eventManager.on("viewDoc", (doc) => {
this.loadDocuments(doc.id);
});
};
componentDidUpdate(prevProps, prevState, snapshot) {
this.updateDoc()
}
componentDidMount() {
this.updateDoc()
}
render() {
return <Translation>
{(t) => {
if (this.state.loading) {
return (
<div style={{display: 'flex', justifyContent: 'center'}}>
<Spin size={"medium"}/>
</div>
)
}
if (this.state.metaInfoDocs.length === 0) {
return (
<div style={{display: 'flex', justifyContent: 'center'}}>
<NoDocumentsAlert><div dangerouslySetInnerHTML={{__html: t('noDocuments')}}/></NoDocumentsAlert>
</div>
)
}
return (
<DocViewWrapper docs={this.state.docs}
metaInfoDocs={this.state.metaInfoDocs.map(doc => {
return {...doc, type: this.props.type}
})}
eventManager={this.props.eventManager}
settings={this.props.settings}
childComponents={this.props.childComponents}
/>
)
}}
</Translation>
}
loadDocuments(id) {
this.props.loadDocument(id).then(r => {
this.setState({
docs: r.data
})
});
}
}
Try replacing ComponentDidUpdate from
componentDidUpdate(prevProps, prevState, snapshot) {
this.updateDoc()
}
To
componentDidUpdate(prevProps, prevState, snapshot) {
if(this.props !== prevProps){
this.updateDoc()
}
}
You can be more specific to didUpdate what to check instead of checking complete props change.

React items.map is not a function when items is an array?

Loading in an API and I'm getting .map isn't a function. Been looking through every example and followed them exactly but still getting this error. The error is of course happening at the .map in the ul tag
class Login extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
isLoaded: false
};
}
componentDidMount() {
fetch(
"https://opentdb.com/api.php?amount=10&category=18&difficulty=easy&type=boolean"
)
.then(res => res.json())
.then(json => {
this.setState({ isLoaded: true, items: json });
});
}
render() {
var { isLoaded, items } = this.state;
if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="App">
<ul>
{items.map(item => (
<li key={item.results.question}>{item.results.question}</li>
))}
</ul>
</div>
);
}
}
}
export default Login;
Your actual data is coming in json.results, so you need to set json.results in state like,
this.setState({ isLoaded: true, items: json.results });
You need to iterate array like,
{ items.map(item => (
<li key={item.question}>{item.question}</li>
))}
Demo

Fetch data with react and componentDidMount

I try to get some data from an api but for some reason it's not working.
Normally when i try to fetch data this way it's working fine
class App extends Component {
constructor() {
super();
this.state = {
items: []
};
}
componentDidMount() {
this.getData();
}
getData() {
fetch(url)
.then(results => results.json())
.then(results => this.setState({ items: results }));
}
render() {
const {items} = this.state;
return (
<ul>
{items.map(function(item, index) {
return (
<div>
<li><h1>{console.log(item.title)}</h1></li>
</div>
);
}
)}
</ul>
);
}
}
I got this error in the browser
TypeError: items.map is not a function

Material UI Switch does not update immediately in React

I have a row component that contains all information about a project and a switch that shows the active status of the project (T or F).
render() {
const dateDisplay = moment(this.props.createdAt).format('MMM YYYY');
return (
<tr
className="experiment-list__row"
onMouseOver={() => this.props.onRowHovered(this.props.rowItems.id)}
>
<td>{this.props.rowItems.name}</td>
<td>{this.props.rowItems.owner}</td>
<td>{dateDisplay}</td>
<td className="experiment-list--col__switch">
<Switch
color="primary"
checked={this.props.rowItems.status}
onChange={()=>{this.handleSubmit(this.props.rowItems.id, this.props.rowItems.status)}}
/>
</td>
</tr>
);
}
It looks like this. When I click the switch it is supposed to toggle and change the status based on the current status. The handleSubmit does it for me.
handleSubmit(rowID: any, rowStatus: any) {
console.log(rowID, rowStatus)
makeMutation(UpdateExperimentQuery, {
update: {
id: rowID,
data: {
status: !rowStatus
},
},
})
.then(responseData => {
console.log(responseData)
})
.catch(err => {
console.log(err);
});
}
It updates the data correctly.
However, it does not get updated immediately even though the checked attribute of the switch represents the status of the row.
When I refresh it, it changes, but I want it to show it immediately since that's the point of using react.
Please help
EDIT
Displays the Info
<div className="experiments-list-container">
<List
onRowHovered={this.getExperimentID}
rowItems={this.state.experimentData}
/>
</div>
This is a different Component ListRow
const List = props => {
return (
<table className="experiment-list">
<tbody>
<ListHeader />
{props.rowItems.map((data, i) => (
<ListRow key={i} rowItems={data} onRowHovered={props.onRowHovered} />
))}
</tbody>
</table>
);
};
The render of ListRow
export class ListRow extends Component<ListRowProps, ListRowState> {
constructor(props) {
super(props);
this.state = {
experimentData: [],
status: props.status //unused right now
};
this.handleSubmit = this.handleSubmit.bind(this);
}
// also not used now
componentWillUpdate() {
if (this.state.status !== this.props.status) {
this.setState({
status: this.props.status,
});
}
}
handleSubmit(rowID: any, rowStatus: any) {
console.log(rowID, rowStatus)
makeMutation(UpdateExperimentQuery, {
update: {
id: rowID,
data: {
status: !rowStatus
},
},
})
.then(responseData => {
console.log(responseData)
})
.catch(err => {
console.log(err);
});
}
render() {
const dateDisplay = moment(this.props.createdAt).format('MMM YYYY');
return (
<tr
className="experiment-list__row"
onMouseOver={() => this.props.onRowHovered(this.props.rowItems.id)}
>
<td>{this.props.rowItems.name}</td>
<td>{this.props.rowItems.owner}</td>
<td>{dateDisplay}</td>
<td className="experiment-list--col__switch">
<Switch
color="primary"
checked={this.props.rowItems.status}
onChange={()=>{this.handleSubmit(this.props.rowItems.id, this.props.rowItems.status)}}
/>
</td>
</tr>
);
}
}
EDIT
changeStatus(rowID, rowStatus) {
// close if the selected employee is clicked
console.log(rowID, rowStatus)
makeMutation(UpdateExperimentQuery, {
update: {
id: rowID,
data: {
status: !rowStatus
},
},
})
.then(responseData => {
setTimeout(() => {
this.componentWillMount();
},1000);
console.log('responseData', responseData)
})
.catch(err => {
console.log(err);
});
}
this updates the data and gets called in the List component.
componentWillMount() {
let filteredData = []
//this.props.fetchExperiments();
makeQuery(ExperimentsListQuery)
.then(responseData => {
this.setState(prevState => ({
experimentData: responseData.Experiments,
}));
for(var i = 0; i < this.state.experimentData.length; i++) {
console.log(this.state.experimentData[i])
if(this.state.experimentData[i].status === this.state.viewActive) {
filteredData.push(this.state.experimentData[i])
}
}
this.setState({
filteredExpData: filteredData
})
})
.catch(err => {
//actions.setSubmitting(false);
console.log(err);
});
}
this fetches/filters the data

Categories