How to fix zero return data from itunes api using react fetch

252 Views Asked by At

I am trying to log the data returned from the itunes search api but continue to get a return length of 0 (line 31). When console.logging the URL, the input value and url concat string works as intended (line 32).

The cors-anywhere section of the api url is to defer any cors related errors.

import React, { Component } from "react";

class Search extends Component {
  fetchData() {
    //set search value to a var
    var searchParamater = document.getElementById("searchValue").value;
    console.log("searchParameter is: " + searchParamater);
    var inputValue;
    // check if searchValue has a space in it
    try {
      if (searchParamater === " ") {
        console.log("please type something into the search bar");
      } else if (searchParamater != null && searchParamater.indexOf(" ") > -1) {
        // Search value includes white space
        // find white space / /g and replace with '+'
        inputValue = searchParamater.replace(/ /g, "+");
      } else {
        inputValue = searchParamater;
      }
    } catch (err) {
      console.log(err);
    }

    console.log("inputValue is: " + inputValue);
    let URL = `https://cors-anywhere.herokuapp.com/https://itunes.apple.com/search?term=${inputValue}`;
    console.log(URL);

    fetch(URL) // itunes api link goes here
      .then(response => response.json)
      .then(parsedJSON => console.log(parsedJSON.length))
      .then(parsedJSON => console.log(parsedJSON.result))
      .catch(error => console.log("parsing failed", error));
  }
  render() {
    return (
      <Jumbotron fluid>
        <Container>
          <div />
          <Form>
            <Form.Group controlId="formBasicEmail">
              <Form.Label>
                <h2>Search On iTunes:</h2>
              </Form.Label>
              <Form.Control
                type="text"
                placeholder="Enter search"
                id="searchValue"
              />
              <Form.Text className="text-muted">
                We'll never share your searches with anyone else
              </Form.Text>
            </Form.Group>
            <Button onClick={this.fetchData}>Submit</Button>
          </Form>
          <div />
        </Container>
      </Jumbotron>
    );
  }
}

export default Search;

I would expect to get a logged return JSON object in the console but the json.count object value of 0 tells me that nothing is returning from the API...

1

There are 1 best solutions below

0
On

The fix ended up being in my fetch method now updated to:

fetch(URL)
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(JSON.stringify(myJson));
  });