Reputation: 1469
I have a reactjs page, which consumes an API: ...when tested via postman (GET request), the following results are rendered:
[
{
"clientI": "FedEx KinKOs"
}
]
This is my code:
import React, { Component } from 'react';
import {render} from "react-dom";
import './ClientInfo.css';
class ClientInfo extends Component {
state = {
data:[],
url: "https://jsonplaceholder.typicode.com/todos"
};
componentDidMount() {
fetch(this.state.url)
.then(response => response.json())
.then(data => this.setState({ data }));
}
render() {
const { data } = this.state;
data && console.log(data);
return (
<div>
<div className="container">
<div className="clientContainer">
{data &&
data.map(item =>
<div>
<span>{item.userId} </span>
<span>{item.id} </span>
<span>{item.title} </span>
</div>
)}
</div>
</div>
</div>
);
}
}
export default ClientInfo
...the error occurs on this line of the above code: .then(response => response.json())
could I get some assistance as to what I'm doing wrong?
Upvotes: 2
Views: 4113
Reputation: 3455
Explanation
.then()
twice.response.json()
cannot be called, because you are getting an JSON object back from your endpoint. If there are'nt any callback functions inside, you cannot call the function .json()
on it.setState()
function will be totally enough.Solution
componentDidMount() {
fetch(this.state.url).then(response => {
this.setState({ response });
});
}
Upvotes: 1