Home > Software design >  How to hit an api in react native?
How to hit an api in react native?

Time:01-04

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

CodePudding user response:

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>
);

CodePudding user response:

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();
  }, []);

CodePudding user response:

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,
  },
});

CodePudding user response:

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;

CodePudding user response:

ok guys i had done it by myself :-)

  • Related