Problems attempting to return api data being in a class

-1

I built an api that returns me the units that I have registered in a DB but when trying to return these are not reviewing

import React, { Component } from 'react';
import axios from 'axios';

const api = {

  let: units = [],

  units: () => {
    axios.get('http://192.168.0.23/apiTeste/public/api/unidades')
    .then(response => {
      console.log(response);
        return response.data.data
    }).catch((error) => { 
      console.log(error.message)
    });
    return 'Falha ao tentar retornar as unidades'
  },

};

export default api;

The response returns the data correctly, the response.data.data is used in a file with a class I can define a state units = [] and a setState return the units

But I would like to create this file for the api returns, however as I do not use a class so I understand I can not use the state.

Are there any manners of without the class returning this data, or saving in a variable or something of the sort?

Or use setState right here without a class?

Or in the latter case build a class to be returned in another class that will call the function? Ex:

import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';

import api from './units';

export default class App extends Component { 
  render() {
    return (
      <View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Units: {api.units()}</Text>
      </View>
    );
  }
}

I think these would be the ways to solve my problem, but if anyone knows otherwise than putting the api call in the same file as the final class might be too.

    
asked by anonymous 11.12.2017 / 17:31

1 answer

1

What you can do is to use a Promise() , so you know when you have finished the request and change your state wherever you are.

import React, { Component } from 'react';
import axios from 'axios';

const api = {

let: units = [],

units: New Promisse((resolve, reject)=>{
    axios.get('http://192.168.0.23/apiTeste/public/api/unidades')
    .then(response => {
    console.log(response);
        resolve(response.data.data)
    }).catch((error) => { 
    console.log(error.message)
    reject(error)
    });
});
};
export default api;

api.units.then((result)=>{
    //result vai ser o "response.data.data" que passou para o resolve la em units
    //aqui voce pode usar o setState do component a vontade
}).catch((error)=>{
    //aqui a mesma coisa,o mesmo erro que pega no catch em units
})
    
18.12.2017 / 14:32