Imalea Imalea - 7 days ago 6
iOS Question

Fetching API and make its data accessible across component

I'm fetching an API in one of my components, and sending its data to the

dataAPI
state. It works fine.

But I want to start breaking out my app into smaller components. And I want to be able to access the data from any other component. And I don't want to have to make a different API call each time.

This is the component I have below, where the data is being pulled. What's the best way to access the API's data from across the app?

I'm also currently using a
setInterval()
to refresh the data every minute.

Thanks!

export default class Home extends Component {

constructor(props) {
super(props);

this.state = {
dataAPI: [],
isLoading: true
};

// Refresh data every 60 seconds (60,000 ms)
setInterval(() => {
this.componentDidMount();
}, 60000);

}

componentDidMount() {
this.fetchData();
}

render() {
var {isLoading} = this.state;
if(isLoading)
return this.renderLoadingMessage();
else
return this.renderResults();
}

fetchData() {
var url = 'https://www.myapi.com';
fetch(url)
.then( response => response.json() )
.then( jsonData => {
var myData = [];
console.log(jsonData);
myData.push(jsonData);

this.setState({
isLoading: false,
dataAPI: [].concat(myData)
});
})
.catch( error => console.log('Fetch error ' + error) );
}

renderLoadingMessage() {
return (
<View>
<ActivityIndicator animating={true} />
</View>
);
}

renderResults() {
var {isLoading} = this.state;
var d = this.state.dataAPI[0];

if ( !isLoading ) {
return (
<View>
<Text>
{d.artist}
</Text>
</View>
);
}
}

};


AppRegistry.registerComponent('Home', () => Home);

Answer

you might want to use react redux.

Its a little hard to setup but once u have setup its easy to manage and u get info anywhere in the app refer this link: Getting started with Redux.

It covers different aspects of using redux. Starting off with a simple example of counter. It also deals with how to manage an api call where the result can be accessed anywhere from the app.

Good luck!

Comments