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);
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Amanda Treutler
  • 143
  • 4
  • 12
  • 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. – Heretic Monkey Jan 10 '20 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 – Travis James Jan 10 '20 at 18:57
  • Possible duplicate https://stackoverflow.com/a/45697474/197472 – Duderino9000 Jan 10 '20 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. – Akash Badam Jan 10 '20 at 19:06
  • 1
    Does this answer your question? [fetch() unexpected end of input](https://stackoverflow.com/questions/45696999/fetch-unexpected-end-of-input) – Ali Mousavi Jan 10 '20 at 19:19
  • @AliMousavi Thanks for your help, but that doesn't answer my question. I tried everything mentioned in that post and I'm still getting the same error. The solution given in that post is to update the JSON, but I don't have permission to do so. – Amanda Treutler Jan 10 '20 at 20:26

0 Answers0