React Native Woocommerce Rest Api Fetch Error - react-native

**I am using REACT NATÄ°VE for a project. I need to integrate the website and the mobile application. I have to use WooCommerce Rest API for that. I'm trying to learn but I can't see the data I want to capture. I can not see anything.
**
import WooCommerceAPI from 'react-native-woocommerce-api';
const WooCommerce = new WooCommerceAPI({
url: 'http://myurl', // Your store URL
ssl: true,
consumerKey: '****************',
consumerSecret: '***************',
wpAPI: true, // Enable the WP REST API integration
version: 'v3', // WooCommerce WP REST API version
queryStringAuth: true
});
WooCommerce Config
class X extends Component{
constructor(props) {
super(props);
}
componentWillMount() {
// GET example
return(
WooCommerce.get('products') .then(response => response.json())
.then(responseJson => {
this.setState(prevState => ({
products: [...prevState.products, ...responseJson],
isLoading: false
}));
})
.catch(error => {
console.error(error);
}))
}
<FlatList
data={this.state.products}
renderItem={({item}) => <View>
<Text>{item.name}</Text>
<Text>{WooCommerce.get('products').id}</Text>
</View>}
keyExtractor={item => item.id.toString()}
/>
Data is not fetching, i dont see anything, what is a problem ?

I know my answer might be coming late but for those who are having the same issue. You don't need to add the first then with response.json(). Please look at examples here https://www.npmjs.com/package/react-native-woocommerce-api
componentWillMount() {
// GET example
return(
WooCommerce.get('products')
.then(responseJson => {
this.setState(prevState => ({
products: [...prevState.products, ...responseJson],
isLoading: false
}));
})
.catch(error => {
console.error(error);
}))
}

Related

Re render flat list when data change cause infinite loop React Native

I have two screens. Approve List and Approve Detail. When data approved in Approve Detail, page navigate to Approve List. Then approved data should disapear from FLatList. How to remove FlatList item when data approved? or how to re render FlatList when data change? Here is my code:
Approve List:
const Approve = ({ navigation }) => {
const [rekomendasi, setRekomendasi] = useState({})
// other code
const getRekomendasi = async (token, bagian) => {
try {
const response = await sippApi.get(`/penjaminan?bagian=${bagian}`, {
headers: {
Auth: token
}
});
setRekomendasi(response.data.data)
console.log(rekomendasi)
} catch (error) {
console.log(error)
}
}
useEffect(() => {
getToken();
getUserData()
getRekomendasi(token, userData.bagian);
}, [setToken, setUserData, rekomendasi]); // if I pass rekomendasi here, make infinite loop on api request
return (
<FlatList
onRefresh={() => onRefresh()}
refreshing={isFetching}
removeClippedSubviews
style={{ marginTop: 2 }}
data={rekomendasi}
keyExtractor={rekom => rekom.penjaminan.nomor_rekomendasi}
renderItem={({ item }) => {
return (
<TouchableOpacity onPress={() => navigation.navigate("ApproveDetail", { id: item.penjaminan.nomor_rekomendasi, bagian: userData.bagian })}>
<ApproveList
plafond={item.value}
kantor={item.nama_kantor}
nomor_rekomendasi={item.nomor_rekomendasi}
produk={item.skim}
/>
</TouchableOpacity>
)
}}
showsHorizontalScrollIndicator={false}
/>
)
}
If I pass value on second argument on UseEffect, it cause infinite loop on API request. If not, my FlatList cant re render when data change. What should I do?
Thanks for help
You have to remove the rekomendasi dependency in the useEffect to avoid infinite loop, it's only for init data :)
What is the purpose of onRefresh function in the FlatList ? Instead you could put the getRekomendasi function to trigger a new call and your data will be updated
try to separate the functions to two useEffects
useEffect(() => {
//<-- write your getToken() and getUserDate() here
getToken();
getUserData()
}, []);
useEffect(() => {
const getRekomendasi = async (token, bagian) => {
try {
const response = await sippApi.get(`/penjaminan?bagian=${bagian}`, {
headers: {
Auth: token
}
});
setRekomendasi(response.data.data)
console.log(rekomendasi)
} catch (error) {
console.log(error)
}
}
getRekomendasi(token, userData.bagian);
},[token,userData.bagian]);
Problem solved by using useFocusEffect
useFocusEffect(
React.useCallback(() => {
getRekomendasi(token, userData.bagian)
}, [token, userData.bagian])
);

Display datas with Axios (React Native)

I am trying to display data that I fetched with Axios. They came as an array. Because of this I cant show them. What should I do?
Here is my fetch code
componentDidMount() {
axios.post('http://192.168.1.106:80/partner_project_backend/project_list.php')
.then((response) => {
console.log(response.data)
})
.catch((error) => {
console.error(error);
});
}
Here is my console.log
I'm guessing you are getting the API response correctly and your only intention is to display the data in your application. If so, you could use the FlatList component from React Native
import React from 'react';
import { FlatList, Text } from 'react-native';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
};
}
componentDidMount() {
axios.get('http://192.168.1.106:80/partner_project_backend/project_list.php')
.then((response) => {
this.setState({ data: response.data });
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<FlatList
data={data}
renderItem={({ item }) => (
<Text>{item.name}</Text> // render your view here
)}
keyExtractor={item => item.id}
/>
);
}
}
React more about FlatList at https://reactnative.dev/docs/flatlist
To fetch data you have to use get method NOT post
this.state ={ data : null }
componentDidMount(){
axios.get('http://192.168.1.106:80/partner_project_backend/project_list.php')
.then((response) => {
this.setState({ data : response.data })
})
.catch((error) => {
console.error(error);
});
}

How do I access this rss variable inside my fetch method in React Native?

I'm trying to use react-native-rss-parser (https://www.npmjs.com/package/react-native-rss-parser) to parse my RSS feed and display it on a card but I don't know how to access the rss variable.
fetchRSSFeed() {
return fetch('http://www.nasa.gov/rss/dyn/breaking_news.rss')
.then((response) => response.text())
.then((responseData) => rssParser.parse(responseData))
.then((rss) => { console.log(rss.title) })
}
render() {
{this.fetchRSSFeed()}
return (
<SafeAreaView style={styles.container}>
<Swiper
cards={HomeScreenPics}
renderCard={Card}
infinite
backgroundColor="white"
cardHorizontalMargin={0}
stackSize={2}
/>
</SafeAreaView>
)
}
}
HomeScreenPics = [{
pic: require('../assets/images/news.jpg'),
title: rss.title
}]
console.log(rss.title) works fine. It logs out the RSS feed title but I'm trying to access the rss varible outside the fetch method, I want to parse it into my HomeScreenPics array, but it keeps showing the error: Can't find variable rss
If you want to access the rss variable and pass it to the render function, all you have to do is to use the state that react provides you.
Example:
state = {
feed: {}
}
fetchRSSFeed() {
return fetch('http://www.nasa.gov/rss/dyn/breaking_news.rss')
.then((response) => response.text())
.then((responseData) => rssParser.parse(responseData))
.then((rss) => {
this.setState(prevState => ({
...prevState,
feed: rss
}));
})
}
render() {
{this.fetchRSSFeed()}
return (
<SafeAreaView style={styles.container}>
<Swiper
cards={HomeScreenPics}
renderCard={Card}
infinite
backgroundColor="white"
cardHorizontalMargin={0}
stackSize={2}
/>
<Text>{this.state.feed.title}</Text>
</SafeAreaView>
)
}
}
You can access the response object with the variable this.state.feedin any function.
I recommend you to start from the official documentation: [https://facebook.github.io/react-native/docs/state]
Friendly.
I am actually facing the same issue as you had. xarhsasi answers works like a charm.
Bear in mind that you can avoid calling the function each time since you are willing to render it once, just at the beginning.
I strongly recommend you to add it into a componentDidMount(), like so
constructor(props) {
super(props);
this.state = {
isLoading: true,
feed: {}
}
}
componentDidMount() {
return fetch('http://www.nasa.gov/rss/dyn/breaking_news.rss')
.then((response) => response.text())
.then((responseData) => rssParser.parse(responseData))
.then((rss) => {
this.setState({
isLoading: false,
feed: rss
});
});
}
Then, you only need to call the state like xarhsasi told you with this.state.feed.title, for example.
Best regards,

How to retrieve fetch data in my native app

I would like to know how I can view data from my fetch query in my app.
I have a node that is fetched from React native and I want to display the response.
The node part;
app.get('/balance', function(req, res){
//calling the function
res.jsonp('0');
console.log("CRYPTO CALLED");
});
The react function;
_getBalanceFromApiAsync() {
fetch('http://192.168.1.100:3000/ballance')
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
return responseJson;
})
.catch((error) => {
console.error(error);
});
}
I can see the result in the node console as well as the react console. But where it doesn't work is here.
Native app;
<Text style={styles.getStartedText}>Your Wallet Balance</Text>
<Text> {this._getBalanceFromApiAsync()}</Text>
</View>
The function is getting executed but I would like to display the returned value and as it is the text field remain empty
Thank you
Its simple you need to setState for re-rendering the component. Try doing this
constructor(props){
super(props)
this.state = {
textData: ''
}
}
componentDidMount(){
this.getBalanceFromApiAsync()
}
getBalanceFromApiAsync() {
fetch('http://192.168.1.100:3000/ballance')
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
this.setState({
textData: responseJson
})
})
.catch((error) => {
console.error(error);
});
}
<Text style={styles.getStartedText}>Your Wallet Balance</Text>
<Text> {this.state.textData}</Text>
</View>

How to call fetch() inside renderItem on FlatList?

I have been unable to solve this so far, I hope someone from here can help me :)
The situation is as following:
I load a list of users from a department using an API which returns it as JSON (this works).
For each user in the JSON file, I have to fetch another JSON file containing sensor data (this does not work).
I am in fact capable of getting the JSON data from the getStatus() function, but it is not correct. Because, when the FlatList is rendered, the data still has not been fetched, but on refresh, calling fetchUsers(), the sensor data shows up, but it shows the same sensor data on all users and not their own specific sensor data.
At the moment I have made it spit out what ever JSON it receives in a Text element in order to see what was returned...
I am not allowed to upload pictures here, but I have made an album on Imgur which contains images of the application to help explain the issue: https://imgur.com/a/5XLpR
export default class SensorData extends Component {
constructor(props) {
super(props);
this.stats = null;
this.state = {
isLoading: true,
error: false,
userDataSource: [],
refreshing: false,
time: 30,
navigation: props.navigation,
};
}
componentDidMount() {
this.fetchUsers();
}
fetchUsers(){
return fetch('http://url-to-the-json/json/patients.json')
.then((response) => response.json())
.then((response) => {
this.setState({
isLoading: false,
error: false,
userDataSource: response,
refreshing: false,
time: 30,
}, function () {
});
})
.catch((error) => {
this.setState({
isLoading: false,
error: true
})
});
}
getStatus(patientId) {
fetch("http://url-to-the-json/json/status/" + patientId + ".json")
.then((response) => response.json())
.then((responseJson) => {
this.stats = responseJson;
})
.catch((error) => {
Alert.alert("Error");
});
return this.stats;
};
renderItem(item, index) {
var x = index % 2 === 0;
status = this.getStatus(item.patientId);
return (
<View style={x ? styles.rowEven : styles.rowOdd}>
<TouchableOpacity style={styles.rowName} onPress={this.handlePress.bind(this, item)}>
<Text style={styles.rowNameText}>{item.firstname} {item.lastname}</Text>
</TouchableOpacity>
<Text>{JSON.stringify(status)}</Text>
</View>
)
}
render() {
return (
<View>
<View style={styles.reloadTimer}>
<Text style={styles.timerText}>Reloading in {this.state.time} seconds.</Text>
</View>
<View style={styles.listView}>
<FlatList
data={this.state.userDataSource}
renderItem={({ item, index }) => this.renderItem(item, index)}
keyExtractor={item => item.patientId}
refreshing={this.state.refreshing}
onRefresh={this.handleRefresh}
ItemSeparatorComponent={this.renderSeparator}
/>
</View>
</View>
);
}
}
The variable status is the one in question.
I hope I formulated the question in an understandable manner.
The users JSON file looks like this:
{
"patientId": "ec276ca9-f9ab-429b-b34e-23fcf448d714",
"firstname": "Julie",
"lastname": "Nielsen",
"birthDate": "1930-01-01T00:00:00Z",
"departmentId": "709f59ae-67fe-447c-bed3-7b5912703861",
"patientNumber": null,
"entryDate": null,
"dischargeDate": null,
"editedOn": null,
"editedBy": null
}
The sensor data JSON file looks like this:
{
"status": {
"in_bed": false,
"in_room": true,
"clean_diaper": true
}
}
You need to store the result of getStatus in component state like you do with the patients JSON. Assuming you have a "stats" object in your state that maps a patient to their stats, you can do:
getStatus(patientId) {
fetch("http://url-to-the-json/json/status/" + patientId + ".json")
.then((response) => response.json())
.then((responseJson) => {
let stats = Object.assign({}, this.state.stats);
stats[patientId] = responseJson;
this.setState({ stats: stats });
})
.catch((error) => {
Alert.alert("Error");
});
};
Then, in the renderItem function, you can render the stats from state, or render a placeholder text if the stats haven't been loaded yet.
Also, you should not make network requests inside a render function, since they can be called quite often and multiple times for the same component. Instead, you should look into the FlatList API and the callbacks for changes in visibility.
Hope this helps...