Home > front end >  Fecth JSON URL in React Native
Fecth JSON URL in React Native

Time:12-02

I am trying to obtain the data from this website: https://reactnative.dev/movies.json

I use the following code:

fetch("https://reactnative.dev/movies.json")
    .then(response => response.json())
    .then((responseJson) => {
        
        setTimeout(() => {
            this.setState({
                loading: false,
                dataSource: responseJson
            })
        }, 2000)

        Alert.alert(responseJson)

    })
    .catch(error => console.log(error))


    return (
        <FlatList
            data={DATA}
            renderItem={renderItem}
            keyExtractor={item => item.id}
            refreshControl={
                <RefreshControl refreshing={refreshing} onRefresh={this.onRefresh} tintColor={themes[theme].auxiliaryText} />
            }
        />

    
    );
};

My problem is that Alert.alert (responseJson) throws the following error: This error

... and I would like to get the data for the flatlist.

Who helps me, please?

CodePudding user response:

You must print your response data by console.log and make sure what the response data is. According to your error, I think you are getting Object type data after fetching, but you need to assign String into Alert.alert, therefore I suggest you try the following.

Alert.alert(responseJson.title)

CodePudding user response:

I just tested this code it seems to be working. Is that what you are looking for?

with currElement you have access to the filmed object.

import { useEffect, useState } from "react"
function Home() {
  const [isLoading, setLoading] = useState(true)
  const [data, saveData] = useState([])

  useEffect(() => {
    fetch("https://reactnative.dev/movies.json")
      .then(response => response.json())
      .then(responseJson => {
        console.log(responseJson.movies)
        saveData(responseJson.movies)
        setLoading(false)
      })
      .catch(error => console.log(error))
  }, [])
  console.log(data)

  return isLoading ? (
    <p> i am loading</p>
  ) : (
    <ul>
      {data.map(currElement => (
        <li key={currElement.id}> {currElement.title}</li>
      ))}
    </ul>
  )
}

  • Related