Home > Back-end >  Getting data from Wordpress with API to React Native app with Expo
Getting data from Wordpress with API to React Native app with Expo

Time:12-15

I hope this question isn't answered somewhere, but I've Googled for hours and I don't understand anything anymore. So... I'm a beginner with React Native and we are making apps with Expo. For the exam, I need to make an app with products from a database. I had to make this 'webshop database' in Wordpress. You can find the overview of products here: https://evivermeeren.com/2233-2/

To start, I need to make a simple page where I list all the items (the suitcases) in an overview. If I could get that and understand how that works, the rest will be fine. I just can't get my head around the whole getting information from an API thing. I mean, I get the concept, but I don't know how to put the info on my screen.

This is the example my teacher gave me. I can't ask my teacher, since his wife is having a baby so we need to figure this out by ourselves.

import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, FlatList, TextInput } from 'react-native';

import apiKey from '../apiKey';
import MovieItem from '../components/MovieItem';

const MoviesScreen = ({ navigation }) => {

  const [movies, setMovies] = useState([]);

  const getMoviesByRating = async () => {
    try {
      const response = await fetch("https://moviesminidatabase.p.rapidapi.com/movie/order/byRating/", {
        "method": "GET",
        "headers": {
          "x-rapidapi-host": "moviesminidatabase.p.rapidapi.com",
          "x-rapidapi-key": apiKey
        }
      })
      const json = await response.json();
      console.log(json);
      setMovies(json.results);
    } catch (error) {
      console.error(error);
    }
  }

  useEffect(() => {
    getMoviesByRating();//laad moviesByRating wanneer het scherm laadt
  }, []);


  return (
    <View style={styles.screen}>
      <FlatList
        data={movies}
        keyExtractor={item => item.imdb_id}//gebruik imdb_id als key voor de flatlist
        renderItem={({ item }) => (

          <Text>{item.rating} - {item.title}</Text>

        )}
      />
    </View >
  );
}

const styles = StyleSheet.create({
  screen: {
    padding: 50,
  }
});
export default MoviesScreen;

This gives a list of movie items, by their rating. For my question, I just want to have a list of all my suitcases, I don't care in which order or even if it's just the title.

Because I work with WooCommerce, I need to use a customer key and a customer secret. I have those and I also have my API Key from my Wordpress website via Akismet. So it's important that I put this in the code too.

This is what I have now, but it shows nothing.

import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, FlatList, TextInput } from 'react-native';

import apiKey from '../apiKey';
import productItem from '../components/products';

const HomeScreen = ({ navigation }) => {

    const [title, setTitle] = useState([]);
  
    const getTitle = async () => {
      try {
        const response = await fetch("https://evivermeeren.com/wp-json/wp/v2/posts/1629", {
          "method": "GET",
          "headers": {
            "x-rapidapi-host": "evivermeeren.com",
            "x-rapidapi-key": apiKey
          }
        })
        const json = await response.json();
        console.log(json);
        setTitle(json.results);
      } catch (error) {
        console.error(error);
      }
    }
  
    useEffect(() => {
        getTitle();
    }, []);
  
  
    return (
      <View style={styles.screen}>
        <FlatList
          data={title}
          keyExtractor={item => item.author}
          renderItem={({ item }) => (
  
            <Text>{item.title}</Text>
  
          )}
        />
      </View >
    );
  }
  
  const styles = StyleSheet.create({
    screen: {
      padding: 50,
    }
  });

  export default HomeScreen;

This is the App.js file:

import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

import HomeScreen from './screens/Home.js';

const Stack = createNativeStackNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

I just get a screen with 'home' at the top, the rest is empty.

Can someone PLEASE give me a proper explanation, or give me a link to a website, video... where this is explained in 'dumb-people-language'? I would be forever grateful! This assignment counts for 50% of my class and I really can't figure it out. If I could just have an example of my own website in an app, I will figure out the rest by myself. And yes, I sound desperate, but that is because I have been looking for the answer for 6 hours now and it just doesn't work! :(

CodePudding user response:

To fetch products from WooCommerce with authentication in React Native, you can use the fetch method and include the necessary authentication information in the request headers. Here is an example of how you might do this:

fetch('https://your-store.com/wp-json/wc/v3/products', {
  headers: {
    'Authorization': 'Basic '   base64.encode('username:password')
  }
})
  .then((response) => response.json())
  .then((products) => {
    // do something with the products here
  });

Make sure to replace https://your-store.com with the URL of your WooCommerce store, and username and password with your WooCommerce API credentials.

You may also need to provide additional authentication information, such as an API key or OAuth token, depending on how your WooCommerce store is configured. Consult the WooCommerce API documentation for more information.

Example with bearer token :

fetch('https://your-store.com/wp-json/wc/v3/products', {
  headers: {
    'Authorization': 'Bearer '   yourBearerToken
  }
})
  .then((response) => response.json())
  .then((products) => {
    // do something with the products here
  });


  • Related