skip to Main Content

I am making a function of API and calling it use Effect and keeping this all in use state but I am getting a blank space!

function api() {
    var requestOptions = {
      method: 'GET',
      redirect: 'follow',
    };

    fetch('https://simple-books-api.glitch.me/books/2', requestOptions)
      .then(response => response.text())
      .then(result => console.log(result))
      .catch(error => console.log('error', error));
    // const [count, setCount] = useState(0);
  }
  const [count, setCount] = useState(api);
  const [modalVisible, setModalVisible] = useState(false);
  const [item, setitem] = useState();
  const [message, setMessage] = useState(api);
  useEffect(() => {
    api();
  });

I want to get results of API.

4

Answers


  1. There is a few mistakes with your code. Here is how you should implement it :

    const [count, setCount] = useState(0);
    const [message, setMessage] = useState('');
    
    useEffect(() => {
      api();
    }, []);
    
    function api() {
      var requestOptions = {
        method: 'GET',
        redirect: 'follow',
      };
    
      fetch('https://simple-books-api.glitch.me/books/2', requestOptions)
        .then(response => response.text())
        .then(result => {
          console.log(result);
          setCount(result.count);
          setMessage(result.message);
        })
        .catch(error => console.log('error', error));
    }
    

    Like this, message and count states will have datas.

    You can display it in your return statement.

    For example :

    return (
      <Text>
        Count: {count}
        Message: {message}
      </Text>
    );
    
    Login or Signup to reply.
  2. You forgot to enter [] prop for useEffect and set state value after fetching data. You can try the below code:

    function api() {
        var requestOptions = {
          method: 'GET',
          redirect: 'follow',
        };
    
        fetch('https://simple-books-api.glitch.me/books/2', requestOptions)
          .then(response => response.text())
          .then(result => {
             console.log(result);
             setMessage(result);
          })
          .catch(error => console.log('error', error));
      }
    
      const [count, setCount] = useState(api);
      const [modalVisible, setModalVisible] = useState(false);
      const [item, setitem] = useState();
      const [message, setMessage] = useState('');
    
      useEffect(() => {
        api();
      }, []);
    
    Login or Signup to reply.
  3. Replace your API in the below code:

    import React, { useEffect, useRef, useState } from 'react';
    import { Text, View, StyleSheet } from 'react-native';
    import Constants from 'expo-constants';
    
    export default function App() {
      const [count, setCount] = useState(0);
    
      useEffect(() => {
        apiCall();
      }, []);
    
      function apiCall() {
        fetch('https://reactnative.dev/movies.json')
          .then((response) => response.json())
          .then((json) => {
            console.log('movies', json.movies);
            setCount(json.movies.length);
            return json.movies;
          })
          .catch((error) => {
            console.error(error);
          });
      }
    
      return (
        <View style={styles.container}>
          <Text>Total: {count}</Text>
        </View>
      );
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        paddingTop: Constants.statusBarHeight,
        backgroundColor: '#ecf0f1',
        padding: 8,
      },
    });
    
    Login or Signup to reply.
  4. Here is the simple fetch API structure in React Native functional component.

    import React, {useState, useEffect} from 'react';
    import {View, Text, ActivityIndicator} from 'react-native';
    
    const FetchExample = () => {
      const [isLoading, setLoading] = useState(true);
      const [data, setData] = useState([]);
    
      useEffect(() => {
        fetch('https://jsonplaceholder.typicode.com/todos/1')
          .then((response) => response.json())
          .then((json) => setData(json))
          .catch((error) => console.log(error))
          .finally(() => setLoading(false));
      }, []);
    
      return (
        <View style={{flex: 1, padding: 24}}>
          {isLoading ? (
            <ActivityIndicator />
          ) : (
            <View>
              <Text>{data.title}</Text>
            </View>
          )}
        </View>
      );
    };
    
    export default FetchExample;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search