Fetch in React.js not working

15,148

Solution 1

I think your fetch code looks ok, are any errors being thrown in the console? It might be your handler not being bound to the correct context. If you don't bind the function correctly, the this.setState will cause an error because this is not the correct context. You might want to bind it in the constructor, or even better, use an initializer like this:

handleFormSubmit = (item) => {
  const url = `https://api.aladhan.com/timingsByCity?city=${item}&country=US&method=2`;

  fetch(url)
    .then((response) => {
     return response.json();
    })
    .then((json) => {
      this.setState({
        Fajir: json.Fajir,
        Sunrise: json.Sunrise,
        Dhuhr: json.Dhuhr
      });
    });
}

One thing to do is check your browser's network developer tab and make sure the request is going through correctly.

Update

Looks like it's working now, see the fetch code below:

const item = 'Chicago';
    var url = 'https://api.aladhan.com/timingsByCity?city=' + item + '&country=US&method=2';

fetch(url)
  .then((response) => {
    return response.json();
  })
  .then((json) => {
    console.log(json);
  });

Solution 2

hey try this fiddle it is working just open the console it is logging out the response. Fiddle Link

HTML

<div id="container"></div>

JS

class Hello extends React.Component {
handleFormSubmit = (item) => {
  const url = 'https://api.aladhan.com/timingsByCity?city='+item+'&country=US&method=2';
  fetch(url)
    .then((response) => {
        console.log(response);
     return response.json();
    })
    .then((json) => {
      this.setState({
        Fajir: json.Fajir,
        Sunrise: json.Sunrise,
        Dhuhr: json.Dhuhr
      });
    });
}
  render() {
    return <button onClick={() => this.handleFormSubmit(2)}>Click Me</button>;
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);
Share:
15,148
Zubair Amjad
Author by

Zubair Amjad

Updated on June 06, 2022

Comments

  • Zubair Amjad
    Zubair Amjad almost 2 years

    I am trying to do a fetch request in react.js and I don't seem to be fetching anything. I feel as though it is a stupid mistake and I am not noticing it. Any help would be appreciated.

    import React, {Component} from 'react';
    import './App.css';
    import TimeSearch from './TimeSearch.jsx';
    import CurrentTime from './CurrentTime.jsx';
    
    class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          list: []
        };
      }
    
      handleFormSubmit(item) {
        var url = 'https://api.aladhan.com/timingsByCity?city=' + item + '&country=US&method=2';
    
        fetch(url)
          .then(response => {
            return response.json();
          })
          .then(json => {
            this.setState({
              Fajir: json.Fajir,
              Sunrise: json.Sunrise,
              Dhuhr: json.Dhuhr
            });
          });
      }
    
      render() {
        return (
          <div className="App">
            <h1>Welcome to Prayer Times!</h1>
            <h6>Search for times in any city in the United States</h6>
            <TimeSearch
              handleFormSubmit={item => {
                this.handleFormSubmit(item);
              }}
            />
            <CurrentTime Fajir={this.state.Fajir} />
          </div>
        );
      }
    }
    
    export default App;
    
    // Time Search Component
    
    import React, {Component} from 'react';
    
    class TimeSearch extends Component {
      render() {
        return (
          <ul>
            <form onSubmit={e => this.handleFormSubmit(e)}>
              <input type="text" id="lookUp" placeholder="Search by City" ref="seachBox" />
              <button type="submit" id="searchButtons">
                {' '}
                Search{' '}
              </button>
            </form>{' '}
          </ul>
        );
      }
      handleFormSubmit(e) {
        e.preventDefault();
        var item = this.refs.searchBox.value;
        this.props.handleFormSubmit(item);
      }
    }
    
    export default TimeSearch;
    
    // Current Time Component
    
    import React, {Component} from 'react';
    
    class CurrentTime extends Component {
      render() {
        return (
          <div id="time">
            <h1 id="fajir"> {this.props.Fajir} </h1>
          </div>
        );
      }
    }
    
    export default CurrentTime;

    Update https://i.stack.imgur.com/YJx9T.png

    Nothing shows up when I log the which is confusing me and I tried making an API request using Postman windows application and it works 100% fine so I have no clue what is going on now

  • Zubair Amjad
    Zubair Amjad over 6 years
    Hey, so I did check the network tab and it seems like the fetch request is not in there, it is showing nothing in there. It means nothing is being fetched
  • Zubair Amjad
    Zubair Amjad over 6 years
    Hey Philipp, I have updated my post! It will have the components!
  • Austin Greco
    Austin Greco over 6 years
    @ZubairAmjad Seems to be working now, I think https might work cross domain, but http didn't
  • Zubair Amjad
    Zubair Amjad over 6 years
    I am trying to log it and for some reason it is not letting me log on my browser, and nothing is being logged in the browser
  • Philipp Wrann
    Philipp Wrann over 6 years
    It looks okay, the fetch does work from dev-tools. I noticed you need to handle the json differently: json.data.timings contains your desired properties.
  • Zubair Amjad
    Zubair Amjad over 6 years
    Hey Phillipp, so it would be something like json.data.timings.Fajir right?
  • Zubair Amjad
    Zubair Amjad over 6 years
    Turns it out when I created a react app it messed up somewhere did that and it worked!