Ad

Can't Retrieve The Data From This API

- 1 answer

I have developed this live search component in react which retrieves data from an API according to the input search value. However it doesn't retrieve or display the data when pointed to this API https://api.itbook.store/1.0/search/program

But when i use an API like for example: http://hn.algolia.com/api/v1/search?query=redux it retrieves data

  const [data, setData] = useState({ books: [] });
  const [query, setQuery] = useState('program');
  const [url, setUrl] = useState(
    'https://api.itbook.store/1.0/search/program',
  );

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(url);

      setData(result.data);
    };

    fetchData();
  }, [url]);

  return(
    <Paper className={classes.root}>

      <Container maxWidth="lg">

        <form className={classes.container} encType="multipart/form-data">

          <TextField
            required
            id="standard-required"
            placeholder="Enter Book Name"
            label="Search for a Book"
            name="bookName"
            value={query}
            onChange={event => setQuery(event.target.value)}
            className={classes.textField}
            multiline
            rowsMax="2"
          margin="normal"/>

          <Button onClick={() =>
            setUrl(`https://api.itbook.store/1.0/search/${query}`)
          }
            className={classes.button} color="primary">Search</Button>

          <ul>
            {data.books.map(item => (
              <li key={item.objectID}>
                <a href={item.url}>{item.title}</a>
              </li>
            ))}
          </ul>


        </form>

      </Container>

    </Paper>

I want my code to collect the data from the API Json : https://api.itbook.store/1.0/search/something

Ad

Answer

@sideshowbarker delivers an excellent solution to this problem Trying to use fetch and pass in mode: no-cors

Essentially what you can do to workaround the CORS issue is make your request via CORS Proxy URL.

Here's a working sandbox with updates to your code: https://codesandbox.io/s/lucid-kapitsa-w1uid

import React, { useState } from "react";
import ReactDOM from "react-dom";
import axios from "axios";

import "./styles.css";

const App = () => {
  const [url, setUrl] = useState("https://api.itbook.store/1.0/search/");
  const [query, setQuery] = useState("");
  const [results, setResults] = useState([]);

  const fetchData = async () => {
    const proxyURL = "https://cors-anywhere.herokuapp.com/";
    const updatedURL = `${proxyURL}${url}${query}`;
    const res = await axios(updatedURL);

    setResults(res.data.books);
  };

  const createBookList = () => {
    return results.map(book => {
      return (
        <div>
          <h4>{book.title}</h4>
        </div>
      );
    });
  };

  return (
    <div>
      <input onChange={e => setQuery(e.target.value)} value={query} />
      <button onClick={fetchData}>Click</button>
      <div>{createBookList()}</div>
    </div>
  );
};
Ad
source: stackoverflow.com
Ad