3

I am learning React.js and trying to fetch API like this

constructor() {
    super();

    this.state = {person: []};
}

componentDidMount() {
    fetch('https://randomuser.me/api/?results=500', {mode: 'no-cors'})
            .then(results => {
                return results.json();
            })
            .then(data => {
                let person = (data.results || []).map((pic) => {
                    return(
                            <div key={pic.results}></div>
                            )
                })

                this.setState({person: person});
                console.log("state", this.state.person);
            })
}

render() {

    return (
            <div>
                {this.state.person}
            </div>
    );
}

and this is the error I get

http://prntscr.com/k36ggq

I am pretty new in this, so if anyone can help me with this that would be great. Thanks

Yannick Loriot
  • 7,107
  • 2
  • 33
  • 56
mare
  • 81
  • 1
  • 1
  • 9
  • 1
    You are using mode as "no-cors". You cannot use javascript to parse the result if you are using "no-cors". – Ragul Parani Jul 06 '18 at 07:04
  • 2
    Seem to be already answered here: https://stackoverflow.com/questions/43317967/handle-response-syntaxerror-unexpected-end-of-input-when-using-mode-no-cors/43319482 – Nicklaus Brain Jul 06 '18 at 07:10
  • 3
    Possible duplicate of [Handle response - SyntaxError: Unexpected end of input when using mode: 'no-cors'](https://stackoverflow.com/questions/43317967/handle-response-syntaxerror-unexpected-end-of-input-when-using-mode-no-cors) – Ryan C Jul 06 '18 at 07:19

3 Answers3

2

Try by setting the header as follows. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS You just remove the mode: 'no-cors' in your code,

componentDidMount() {
    fetch('https://randomuser.me/api/?results=500')
    .then(response =>  response.json())
    .then(resData => {
       //console.log(JSON.stringify(resData))
       //do your logic here       
       //let person = resData.results
       this.setState({ person: resData.results }); //this is an asynchronous function
    })
}

render(){

  return(
  <div>
    { 
      this.state.person.map((personRecord) => {
        return <div key={personRecord.id.value}> {personRecord.name.first} </div>
      })
    }
  </div>
  )
}

//sample result json 
{
"results": [ //we already fetched the results array of object from resData
        {
            "gender": "female",
            "name": {
                "title": "mrs",
                "first": "astrid",
                "last": "jørgensen"
            },
            "location": {
                "street": "2675 strandgårdsvej",
                "city": "hurup thy",
                "state": "danmark",
                "postcode": 63288,
                "coordinates": {
                    "latitude": "-27.6956",
                    "longitude": "104.8135"
                },
                "timezone": {
                    "offset": "+5:30",
                    "description": "Bombay, Calcutta, Madras, New Delhi"
                }
            },
            "email": "astrid.jørgensen@example.com",
            "login": {
                "uuid": "25ab4c50-9a8c-48bc-a276-acae2209aa19",
                "username": "happymouse810",
                "password": "journey",
                "salt": "OGXHTU6k",
                "md5": "5c659a3d97b081fc18f0bf94f246751d",
                "sha1": "407020d4230121788180244775edd6fbea56c375",
                "sha256": "0cc94ec5d89f71903c9f74dcd12253240b1269e75a3ca67eae3f4d578e47d3f8"
            },
            "dob": {
                "date": "1978-03-28T17:31:08Z",
                "age": 40
            },
            "registered": {
                "date": "2017-04-19T14:15:02Z",
                "age": 1
            },
            "phone": "10566067",
            "cell": "24745172",
            "id": {
                "name": "CPR",
                "value": "295410-3587"
            },
            "picture": {
                "large": "https://randomuser.me/api/portraits/women/12.jpg",
                "medium": "https://randomuser.me/api/portraits/med/women/12.jpg",
                "thumbnail": "https://randomuser.me/api/portraits/thumb/women/12.jpg"
            },
            "nat": "DK"
        }
    ]
}

//By using this way we can able to get the result, but it just delays
fetch('https://randomuser.me/api/?results=500')
.then(response =>  response.json())
.then(resData => console.log(resData))
Jeeva
  • 1,550
  • 12
  • 15
  • 1
    That's a **response** header, not a request header. – Quentin Jul 06 '18 at 08:51
  • @mare, remove the mode from your fetch request and then try it, i have updated the code, run the snippet above to double check it, it will take some time to load the results – Jeeva Jul 06 '18 at 10:00
  • @Jeeva hey, thanks a lot for your effort but I am still geting this error http://prntscr.com/k39k5x ...results are undefined. Where should I define results? Sorry for bothering you, but I am new at all this – mare Jul 06 '18 at 11:12
  • Are you telling about this error prntscr.com/k3821t – Jeeva Jul 06 '18 at 11:14
  • do your logic in the above code where i put the console, may be i will update it with comment in my answer. – Jeeva Jul 06 '18 at 11:18
  • I have updated my answer. kindly check it and let me know if any – Jeeva Jul 06 '18 at 11:38
  • @Jeeva hey, looks like that fix that error... But now, I got this in console http://prntscr.com/k3a15k and this is how my code look right now `componentDidMount() { fetch('https://randomuser.me/api/?results=500') .then(response => response.json()) .then(resData => { let person = (resData.results || []).map((pic) => { return(
    ) }) this.setState({person: person}); }) }`
    – mare Jul 06 '18 at 11:49
  • yes it may result in error, because you need to set the unique key. since we already got the array of object **results** from **resData**. So only you are iterating using map. updated my answer with the json response that you were getting. you just make your id as your unique key – Jeeva Jul 06 '18 at 11:54
  • now it is telling me that my render method should have return statement, but it do. Why is so hard to fetch API :( – mare Jul 06 '18 at 12:19
  • Sorry its my mistake, i wrote the render method without return in it, i have updated it now – Jeeva Jul 06 '18 at 12:29
0

Change mode to cors will solve your problem I guess.

 fetch('https://randomuser.me/api/?results=500', {mode: 'cors'})
duc mai
  • 1,412
  • 2
  • 10
  • 17
0

There are many ways that you can fetch data from your server. so here I am trying to describe two of them.

1. By native browser Fetch API:


const RandomUserContainer = ({children}) => {
  const [data, setData] = useState();

  useEffect(() => {
    fetch('https://randomuser.me/api/?results=500').then(response => {
      
    }).then(jsonData => 
      setData(jasonData)
     )
  }, [])

  return (
    <RandomUserComponent data={data}>
      {children}
    </RandomUserComponent>
  )
}

2. by react-query:

This will give you more synchronized handling like loading, Error, Caching, and more.

First, at the top level of your app, you should provide it.

import { QueryClient, QueryClientProvider } from "react-query";
import RandomUserContainer from "./RandomUserContainer";

const queryClient = new QueryClient()
function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <div className="App">
        <RandomUserContainer count={500}/>
      </div>
    </QueryClientProvider>
  );
}

Then your AdsContainer could fetch data as bellow:

import {useQuery} from "react-query";

const AdsContainer = ({children, count}) => {
  const query = useQuery('todos', async () => {
     const API = `https://randomuser.me/api/?results={count}`;
     const response = await fetch(API);
     return await response.json();
  })

  
  /* logics that depends on your data
   * userEffect(() => {}, [data.length])
   */

  return (
    <RandomUserComponent data={query.data}>
      {children}
    </RandomUserComponent>
  )
}
Heartbit
  • 1,698
  • 2
  • 14
  • 26