AI Reading
Quick summary of this article
This chapter explains how to build a React Native app that handles full CRUD (Create, Read, Update, Delete) operations while also supporting image uploads. It walks through installing the necessary packages, picking images from the device, previewing them, and sending them to a backend API using Axios and FormData.
- Install react-native-image-picker to let users select photos from their device and axios to make HTTP requests.
- Use FormData to send both text data and image files together in a single API request with the header
Content-Type: multipart/form-data. - The Create operation requires an image to be selected first; it then posts the form data to the backend and updates the local list with the response.
- The Update operation can send new text data and optionally a new image; if no new image is chosen, the existing one is kept.
- The Delete operation simply calls the API with the item's ID and removes it from the local state, while best practices include validating file size/type and previewing the image before upload.
6.3 CRUD Operations with Image Upload in React Native
Chapter Overview: In this chapter, you will learn how to perform CRUD operations while handling image uploads. We’ll cover selecting images from the device, previewing them, and sending them to a backend API while performing create, update, and delete operations.
✅ Installing Required Packages
We need libraries for image picking and HTTP requests:
npm install react-native-image-picker
npm install axios
✅ Setting Up Image Picker
Import and configure the image picker:
import React, { useState } from 'react';
import { View, Button, Image, FlatList, Text, Alert } from 'react-native';
import { launchImageLibrary } from 'react-native-image-picker';
import axios from 'axios';
export default function ImageCrudApp() {
const [items, setItems] = useState([]);
const [selectedImage, setSelectedImage] = useState(null);
const pickImage = () => {
launchImageLibrary({mediaType:'photo'}, response => {
if (response.assets) setSelectedImage(response.assets[0]);
});
};
✅ Create Operation with Image
Add a new item with selected image:
const addItem = async () => {
if (!selectedImage) {
Alert.alert('Select an image first');
return;
}
const formData = new FormData();
formData.append('name', 'Sample Item');
formData.append('image', {
uri: selectedImage.uri,
type: selectedImage.type,
name: selectedImage.fileName
});
try {
const res = await axios.post('https://yourapi.com/items', formData, {
headers: {'Content-Type': 'multipart/form-data'}
});
setItems([...items, res.data]);
setSelectedImage(null);
} catch (error) {
console.error(error);
}
};
✅ Read Operation (Display Items)
<FlatList
data={items}
keyExtractor={item => item.id}
renderItem={({item}) => (
<View style={{marginVertical:10}}>
<Text>{item.name}</Text>
<Image source={{uri:item.imageUrl}} style={{width:100, height:100}} />
</View>
)}
/>
✅ Update Operation with Image
Update existing item and optionally change image:
const updateItem = async (id) => {
const formData = new FormData();
formData.append('name', 'Updated Item');
if (selectedImage) {
formData.append('image', {
uri: selectedImage.uri,
type: selectedImage.type,
name: selectedImage.fileName
});
}
try {
const res = await axios.put(`https://yourapi.com/items/${id}`, formData, {
headers: {'Content-Type': 'multipart/form-data'}
});
setItems(items.map(i => i.id === id ? res.data : i));
setSelectedImage(null);
} catch (error) {
console.error(error);
}
};
✅ Delete Operation
const deleteItem = async (id) => {
try {
await axios.delete(`https://yourapi.com/items/${id}`);
setItems(items.filter(i => i.id !== id));
} catch (error) {
console.error(error);
}
};
✅ Tips for Image Upload CRUD
- Always validate image size and type before upload.
- Use FormData to send images via Axios.
- Preview selected image before uploading.
- Handle API errors gracefully with alerts or messages.
- Combine this with local state for responsive UI updates.
✅ Summary
- CRUD operations can be combined with image upload for dynamic apps.
- Use
react-native-image-pickerto select images from device. - Send images using
FormDataandaxiosto backend. - Supports create, read, update, and delete with images seamlessly.
- Preparing you for full-featured apps with media management.
