user1724708
user1724708

Reputation: 1469

Unexpected end of JSON input error

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

Answers (1)

Michael W. Czechowski
Michael W. Czechowski

Reputation: 3455

Explanation

  1. You are using .then() twice.
  2. 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.
  3. Setting the state with your setState() function will be totally enough.

Solution

componentDidMount() {
  fetch(this.state.url).then(response => {
    this.setState({ response });
  });
}

Upvotes: 1

Related Questions