4

I'm trying to fetch data returned from url. Curl to the url results in following:

[{"name": "Hello World!"}]

Following is the code in my App.js


import React, { Component } from 'react';
import Contacts from './components/contacts';


class App extends Component {
  render() {
    return (
      <Contacts contacts={this.state.contacts} />
  )
  }
  state = {
    contacts: []
  };

  componentDidMount() {
    fetch('url')
    .then(res => res.json())
    .then((data) => {
      this.setState({ contacts: data })
    })
    .catch(console.log)
  }

}

export default App;

My contact.js contains the following:

// src/components/contacts.js

import React from 'react'

const Contacts = ({ contacts }) => {
    return (
    <div>
        <center><h1>Contact List</h1></center>
        {contacts.map((contact) => (
        <div class="card">
            <div class="card-body">
            <h5 class="card-title">{contact.name}</h5>
            </div>
        </div>
        ))}
    </div>
    )
};

export default Contacts

The data does not get rendered or logged. Is there an issue in the way I'm fetching it?

EDIT: The issue is related to CORS. Not sure why using flask_cors doesn't resolve it. My server looks like:

from flask import Flask, request, json
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

@app.route("/")
def home():
    return json_response([{"name":"Hello World!"}])

def json_response(payload, status=200):
     return (json.dumps(payload), status, {'content-type': 'application/json'})
4
  • your code looks fine.. are you facing any issue Commented Dec 8, 2019 at 4:00
  • data does not get displayed on the webpage. It should show "Hello World" Commented Dec 8, 2019 at 4:01
  • i posted your code with different api, you can check that Commented Dec 8, 2019 at 4:06
  • can you post the pic of network tab.. the response headers and the preview tab with it ? Commented Dec 8, 2019 at 4:37

1 Answer 1

1

You can check this example of your code with dummy api and your code is working fine.

the only thing is different api

    class App extends React.Component {
      state = {
        contacts: []
      };
      render() {
        return (
          <Contacts contacts={this.state.contacts} />
      )
      }
      componentDidMount() {
        fetch(`https://cors-anywhere.herokuapp.com/http://35.222.96.248:5000/`)
        .then(res => res.json())
        .then(data => {
        this.setState({ contacts: data });
      })
      .catch(console.log);
  }
    }
    const Contacts = ({ contacts }) => {
        return (
        <div>
            <center><h1>Contact List</h1></center>
            {contacts.map((contact) => (
            <div class="card">
                <div class="card-body">
                <h5 class="card-title">{contact.title}</h5>
                </div>
            </div>
            ))}
        </div>
        )
    };

Live Demo

Sign up to request clarification or add additional context in comments.

17 Comments

I followed the same. This works, but if I change the url to the one I want it doen't work. Is there any issue with the response from my url? I have included it in my post
@SrishtiRawal there is no problem with your frontend. the problem is in your api, check that
I used curl to check the response from the api, it seems correct
@SrishtiRawal i already showed you about your frontend code that your code is fine. you need to debug/test your api from postman or something else
Postman returns this: [ { "name": "Hello World!" } ]
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.