React Native - trying to extract the data and store in a variable

Viewed 594

enter image description hereI am new to react-native. I was trying to access the API using fetch. I was able to print the result on the console but was unable to print on a mobile screen. I have attached the screenshot of the practice code below. [enter image description here][2]

import React from 'react'
import { StyleSheet, Text, SafeAreaView} from 'react-native'

const getMoviesFromApi = () => {
  //GET request
  fetch('https://reactnative.dev/movies.json', {
    method: 'GET',
    //Request Type
    //method: 'POST',
  })
    .then((response) => response.json())
    //If response is in json then in success
    .then((responseJson) => {
      //Success
     // alert(JSON.stringify(responseJson));
      //console.log(responseJson);
      return responseJson;
    })
}

const App = () => {
    let data = getMoviesFromApi()
    console.log(data)

     return (

        <SafeAreaView>
          <Text> JSON.stringify{data} </Text>

          {/* <Text> JSON.stringify{parseData} </Text> */}
        </SafeAreaView>
     )
}

const styles = StyleSheet.create({})

export default App

1 Answers

You want to use an useState and keep the data you receive from the api inside state, and useEffect to fetch the data when state updates so will the UI

So I would use something like this:

import { useState, useEffect } from 'react';

const App = () => {
  const [movies, setMovies] = useState([]);

  useEffect(() => {
    const fetchMovies = async () => {
      const data = await getMoviesFromApi();
      setMovies(data); // I supose it's an array of movies
    }
  }, [getMoviesFromApi])

  return (...);
}
Related