0

I'm trying to send a simple fetch in a project that is frontend-only. I was getting a CORS error, so I added mode: "no-cors" to the fetch, following the advice I found on another Stack Overflow question. This resolves the CORS error, but now I'm getting an 'SyntaxError: Unexpected end of input' error. None of the data is being saved to state, so the fetch is not being completed properly. I don't have access to edit the JSON file, but I can't do anything for this exercise without being able to fetch the data.

Here's what I have in my App.js:

import React, { Component } from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  withRouter
} from "react-router-dom";
import ContactList from "./components/ContactList";

class App extends Component {
  constructor() {
    super();

    this.state = {
      contacts: []
    };
  }

  componentDidMount() {
    this.fetchContacts();
  }

  fetchContacts = () => {
    fetch("https://s3.amazonaws.com/technical-challenge/v3/contacts.json", {
      mode: "no-cors"
    })
      .then(resp => resp.json())
      .then(contacts => {
        this.setState({
          contacts: contacts
        });
      })
      .catch(alert);
  };

  render() {
    return (
      <div>
        {this.state.contacts.map(contact => {
          return <p>{contact.name}</p>;
        })}
        <ContactList contacts={this.state.contacts} />
      </div>
    );
  }
}

export default withRouter(App);
6
  • You may want to do a little searching on that error text. It's not uncommon. You'll want to use the Network tab of the Developer Tools on the browser to see what's coming back from your request; it's likely not JSON. Commented Jan 10, 2020 at 18:57
  • I don't think you should need to add "no cors" to the fetch request, because if you send a request to that URL using cURL or postman for example, you will get the result fine. I tested this myself and got a response Commented Jan 10, 2020 at 18:57
  • Possible duplicate stackoverflow.com/a/45697474/197472 Commented Jan 10, 2020 at 19:04
  • You cannot edit the json file but you can read it. It is json array in which every array block have another json array containing contacts which you needed to display. So you need to iterate the array to get contact array. Commented Jan 10, 2020 at 19:06
  • 1
    Does this answer your question? fetch() unexpected end of input Commented Jan 10, 2020 at 19:19

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.