DEV Community

Cover image for Get request with Basic authorization for React Native Mobile application
sayCheese
sayCheese

Posted on

Get request with Basic authorization for React Native Mobile application

Hey Dev Community,

Welcome everyone.

This article is about how to use Fetch API Get request with Basic authorization for React Native Mobile application.

Basic Authentication is when raw(or with basic encoding) username and password is sent to the server, typically in its body

 headers: {
           Authorization: "Basic " + base64.encode(username + ":" + password),

Enter fullscreen mode Exit fullscreen mode

Sending credential pair in 'Authorization' header of a request can be also considered as basic authentication request:

It consists of a prefix Basic (or some other word) and base64 encoding of username and password separated by colon (:)

Authorization key used in header can also be changed to some other name, while the server is configured to parse that key.

Check below code with comments for how I used.

const HomeScreen = () => {
  const [isLoading, setLoading] = useState(true);
  let [data, setData] = useState([]);

  let base64 = require("base-64"); // install it before use from npm i base-64

 const username = "some username goes here";
 const password = "some password goes here";

//function for Fetching data from API
const getMovies = async () => {
   try {
     const response = await fetch(
       "API URL goes here",
       {
         headers: {
           Authorization: "Basic " + base64.encode(username + ":" + password),
         },
       }
     );
     data = await response.json();

     setData(data);

     return data;
   } catch (error) {
     console.error(error);
   } finally {
     setLoading(false);
   }
 };

//use Effect hook
 useEffect(() => {
   getMovies();
 }, []);

return (
    <View style={styles.container}>
//rendering API data in FlatList view
        <FlatList
            keyExtractor={(item) => item.id}
            data={data}
            contentContainerStyle={styles.listCtn}
            renderItem={({ item }) => ( 
          <View style={styles.productImagesCtn}>
                <Image
                  style={styles.productImages}
                  source={{
                    uri: item.images[0].src,
                  }}
                />
          </View>
           )}
         />
       </View>
 );
};

export default HomeScreen;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: "center",
  },

  productImagesCtn: {
    width: Dimensions.get("window").width / 3,
    marginVertical: 20,
  },
  productImages: {
    width: "100%",
    height: 158,
  },
listCtn: {
    justifyContent: "space-around",
    flexDirection: "row",
    flexWrap: "wrap",
  },
});
Enter fullscreen mode Exit fullscreen mode

References used from:

  1. https://newbycoder.com/react_native/auth_basi.
  2. https://stackoverflow.com/questions/34815853/react-native-fetch-and-basic-authentication/71122256#71122256.

Give a suggestions for edit in comments will definitely fix.

Thanks for Reading.

Top comments (0)