0

I am very new to react native and try to create my first app. I now want to create functions to get data from my api. How can I create a file with several functions (like in php) to get the data from my api.

For example:

  • get_user()
  • get_customer(customer_id)
  • get_adress(user_id) and a lot more getter.

New helper function: (file=Data_funks.js):

import React from 'react'
import { Image, StyleSheet } from 'react-native'
import clientConfig from '../../client-config';


const helpers = {
    
    helper1: function(user_id){
        
         const get_bauleiter = async () => {
            try {   
                  const siteUrl = clientConfig.siteUrl + '/wp-json/zep/v1/' + user_id;
                  const response = await fetch(siteUrl, {
                        method: 'GET',
                        headers: {
                             Authorization: 'Bearer '+localStorage.getItem( 'token' )
                        }
                  })

            if (response.status === 200) {  


                                let json = await response.json();
                                const array = json.data;
                                const error = array.error_code; 
                                const my_array=array.data_values[0][0];
                

                    if(error == 0){ 


                        var result =Object.entries( my_array );
//var result = Object.entries(my_array).map((key,values) => [key, my_array[key]]);
        
                        await localStorage.setItem( 'test', result);

                        return result;
                        
                        
                    }else{
                        
                        setData(1201);
                        
                    }

                }else {
                    
                        setData(1200);
                    
                }

                    } catch (err) { 
                        
                         console.log(err);  
                        
                    }
            }   
             
        get_bauleiter();     
             
        } //end helper1
    
} // end helpers


export default helpers;

Now I use to get the Array in this function here but it doesen´t work:

...
import React from 'react'
import {Alert, View, Text, Modal, StyleSheet, ImageBackground, ScrollView, TouchableOpacity, Linking} from 'react-native'

import Background from '../components/Background_2';
import BackButton from '../components/BackButton';
import funcs from '../components/Data_funks';

import Icon2 from 'react-native-vector-icons/Ionicons';



//##################### ICONS Importieren ##################### 
import AppLoading from 'expo-app-loading';
import { useFonts } from 'expo-font';
import { createIconSetFromIcoMoon } from '@expo/vector-icons';


const Icon = createIconSetFromIcoMoon(
  require('../../assets/icomoon/selection.json'),
  'IcoMoon',
  'zepra_icons.ttf'
);

//#############################################################




export default function ProjectsScreen({ route, navigation }) {

      const { data }    = route.params;
      const mail        = data.item.kontakte_mail;
      const test        = funcs.helper1(data.item.projekt_id);
      const testData    = localStorage.getItem( 'test' ); 
    
        var myArray = testData.split(',');
    
    
        var myArray = myArray.filter(n => n);

        console.log(myArray);

    

What I receive is this:

Array [ "contact_id", "1", "contact_unternehmen", "47", "contact_anrede", "Frau", "contact_titel", "Dr.", "contact_infos", "Testinfo", "contact_vorname", "Olivia", "contact_nachname", "Candal", "contact_position", "Öffentlichkeitsarbeit", "contact_strasse", "Pariser Straße", " 2", "contact_zipcode", "589885", "contact_ort", "Limburg an der Lahn", "contact_land", "Deutschland", "contact_telefon", "+49 (0)654545454454454545", "contact_telefax", "+49 (0)654545454454454545", "contact_mobil", "+49 (0)654545454454454545", "contact_mail", "olivia.candal@blabla.com", "contact_buero", "VDT e.V.", ]


sinan_u
  • 59
  • 2
  • 8

1 Answers1

0

Check this demo, where I have returned different types of data: Helper Demo

Harsh Patel
  • 688
  • 2
  • 5
  • 16
  • Your example is working if the function is setup like in your example. But how does it work in my exammple? It is not workin. I added the new function at the end of my question. How to use it in an async fetch function? I need your help please. – sinan_u May 11 '22 at 11:14
  • You need to use "await" while fetching data from storage. like: `const testData = await localStorage.getItem( 'test' ); return testData;` Also you have to place this code after localStorage.setItem( 'test', 'cvcxv' ); – Harsh Patel May 11 '22 at 11:46
  • Hi, Harsh, `const testData = await localStorage.getItem( 'test');` returns an error :Unexpected reserved word 'await' and if I pass `let json = await response.json(); const array = json.data; const testData = await localStorage.setItem( 'test', array ); return testData; ` returns null if I use `const testData = localStorage.getItem( 'test');` – sinan_u May 11 '22 at 15:14
  • try adding 'async' before helper1 function. like. async helper1: function(user_id) – Harsh Patel May 16 '22 at 11:29
  • Tryed it also but is not working. I updated my code above. Could you help me to fix the issue please? I am trying it since a week but it is not working :(( – sinan_u May 16 '22 at 13:54
  • still not getting an array. How can I turn the respond to an array?? – sinan_u May 16 '22 at 14:02
  • Check previous demo, and make changes accordingly: https://snack.expo.dev/@appdelogico/helper-demo – Harsh Patel May 17 '22 at 07:13
  • I tryed your example. Copyed all scripts in my project without any changes, Still receiving the following error: Unhandled promise rejection: TypeError: undefined is not an object (evaluating '_Data_funks.helpers.get_bauleiter'); Data_funks.js is the file where my helper is defined. – sinan_u May 17 '22 at 08:37
  • I made changes in previous demo. check helper.js. I removed const declaration of helper. and wrote functions directly. also in App.js I'm retrieving that data in useEffect. – Harsh Patel May 17 '22 at 10:51