upd: banner

Deskripsi:
- tambah banner
- hapus banner
- edit one banner

- hapus coding contoh tombol upload pada login page

No Issues
This commit is contained in:
amel
2025-05-19 12:13:53 +08:00
parent 5e3b7976e5
commit fb7149ce02
5 changed files with 318 additions and 238 deletions

View File

@@ -1,27 +1,110 @@
import ButtonBackHeader from "@/components/buttonBackHeader" import ButtonBackHeader from "@/components/buttonBackHeader";
import ButtonSaveHeader from "@/components/buttonSaveHeader" import ButtonSaveHeader from "@/components/buttonSaveHeader";
import { InputForm } from "@/components/inputForm" import { InputForm } from "@/components/inputForm";
import Styles from "@/constants/Styles" import Styles from "@/constants/Styles";
import { Entypo } from "@expo/vector-icons" import { apiEditBanner, apiGetBanner, apiGetBannerOne } from "@/lib/api";
import * as ImagePicker from 'expo-image-picker' import { setEntities } from "@/lib/bannerSlice";
import { router, Stack } from "expo-router" import { useAuthSession } from "@/providers/AuthProvider";
import { useState } from "react" import { Entypo } from "@expo/vector-icons";
import { Image, Pressable, SafeAreaView, ScrollView, Text, View } from "react-native" import * as ImagePicker from "expo-image-picker";
import { router, Stack, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import {
Image,
Pressable,
SafeAreaView,
ScrollView,
Text,
ToastAndroid,
View,
} from "react-native";
import { useDispatch } from "react-redux";
export default function EditBanner() { export default function EditBanner() {
const [selectedImage, setSelectedImage] = useState<string | undefined>(undefined) const dispatch = useDispatch();
const { decryptToken, token } = useAuthSession();
const { id } = useLocalSearchParams<{ id: string }>();
const [selectedImage, setSelectedImage] = useState<
string | undefined | { uri: string }
>(undefined);
const [title, setTitle] = useState("");
const [error, setError] = useState(false);
const [imgForm, setImgForm] = useState<any>();
const pickImageAsync = async () => { const pickImageAsync = async () => {
let result = await ImagePicker.launchImageLibraryAsync({ let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ['images'], mediaTypes: ["images"],
allowsEditing: false, allowsEditing: true,
quality: 1, quality: 1,
aspect: [1535, 450],
}); });
if (!result.canceled) { if (!result.canceled) {
setSelectedImage(result.assets[0].uri); setSelectedImage(result.assets[0].uri);
setImgForm(result.assets[0]);
} else { } else {
alert('Tidak ada gambar yang dipilih'); alert("Tidak ada gambar yang dipilih");
}
};
const handleLoadData = async () => {
const hasil = await decryptToken(String(token?.current));
const data = await apiGetBannerOne({ user: hasil, id });
setSelectedImage({
uri: `https://wibu-storage.wibudev.com/api/files/${data.data.image}`,
});
setTitle(data.data.title);
};
useEffect(() => {
handleLoadData();
}, []);
function onValidate(val: string) {
setTitle(val);
if (val == "") {
setError(true);
} else {
setError(false);
}
}
const handleUpdateEntity = async () => {
try {
const hasil = await decryptToken(String(token?.current));
const fd = new FormData();
if (imgForm != undefined) {
fd.append("file", {
uri: imgForm.uri,
type: imgForm.mimeType,
name: imgForm.fileName,
} as any);
} else {
fd.append("file", "undefined",);
}
fd.append(
"data",
JSON.stringify({
title,
user: hasil,
})
);
const updatedEntity = await apiEditBanner(fd, id)
if (updatedEntity.success) {
ToastAndroid.show("Berhasil mengupdate data", ToastAndroid.SHORT);
apiGetBanner({ user: hasil }).then((data) =>
dispatch(setEntities(data.data))
);
router.back();
} else {
ToastAndroid.show('Gagal mengupdate data', ToastAndroid.SHORT);
}
} catch (error) {
console.error(error);
ToastAndroid.show('Gagal mengupdate data', ToastAndroid.SHORT);
} }
}; };
@@ -29,45 +112,65 @@ export default function EditBanner() {
<SafeAreaView> <SafeAreaView>
<Stack.Screen <Stack.Screen
options={{ options={{
headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />, headerLeft: () => (
headerTitle: 'Edit Banner', <ButtonBackHeader
headerTitleAlign: 'center', onPress={() => {
headerRight: () => <ButtonSaveHeader category="update" /> router.back();
}}
/>
),
headerTitle: "Edit Banner",
headerTitleAlign: "center",
headerRight: () => <ButtonSaveHeader
disable={title == "" || error ? true : false}
onPress={() => { handleUpdateEntity() }}
category="update" />,
}} }}
/> />
<ScrollView> <ScrollView>
<View style={[Styles.p15, Styles.mb100]}> <View style={[Styles.p15, Styles.mb100]}>
<View style={[Styles.mb15]}> <View style={[Styles.mb15]}>
{ {selectedImage != undefined ? (
selectedImage != undefined ? ( <Pressable onPress={pickImageAsync}>
<Pressable onPress={pickImageAsync}> <Image
<Image src={selectedImage} style={{ resizeMode: 'contain', width: '100%', height: 100 }} /> src={
</Pressable> typeof selectedImage === "string"
) : ( ? selectedImage
<Pressable onPress={pickImageAsync} style={[Styles.wrapPaper, Styles.contentItemCenter]}> : selectedImage.uri
<View style={{ justifyContent: 'center', alignItems: 'center' }}> }
<Entypo name="image" size={50} color={'#aeaeae'} /> style={{ resizeMode: "contain", width: "100%", height: 100 }}
<Text style={[Styles.textInformation, Styles.mt05]}>Mohon unggah gambar dalam resolusi 1535 x 450 piksel untuk memastikan</Text> />
</View> </Pressable>
</Pressable> ) : (
) <Pressable
} onPress={pickImageAsync}
style={[Styles.wrapPaper, Styles.contentItemCenter]}
>
<View
style={{ justifyContent: "center", alignItems: "center" }}
>
<Entypo name="image" size={50} color={"#aeaeae"} />
<Text style={[Styles.textInformation, Styles.mt05]}>
Mohon unggah gambar dalam resolusi 1535 x 450 piksel untuk
memastikan
</Text>
</View>
</Pressable>
)}
</View> </View>
<InputForm label="Judul" type="numeric" placeholder="Judul" required bg="white" /> <InputForm
{/* <ButtonForm label="Judul"
text="SIMPAN" type="default"
onPress={() => { placeholder="Judul"
AlertKonfirmasi({ required
title: 'Konfirmasi', bg="white"
desc: 'Apakah anda yakin ingin mengubah data?', value={title}
onPress: () => { error={error}
ToastAndroid.show('Berhasil mengubah data', ToastAndroid.SHORT) onChange={onValidate}
router.push('/banner') errorText="Judul tidak boleh kosong"
} />
})
}} /> */}
</View> </View>
</ScrollView> </ScrollView>
</SafeAreaView> </SafeAreaView>
) );
} }

View File

@@ -2,195 +2,153 @@ import ButtonBackHeader from "@/components/buttonBackHeader";
import ButtonSaveHeader from "@/components/buttonSaveHeader"; import ButtonSaveHeader from "@/components/buttonSaveHeader";
import { InputForm } from "@/components/inputForm"; import { InputForm } from "@/components/inputForm";
import Styles from "@/constants/Styles"; import Styles from "@/constants/Styles";
import { apiCreateBanner } from "@/lib/api"; import { apiCreateBanner, apiGetBanner } from "@/lib/api";
import { addEntity } from "@/lib/bannerSlice"; import { setEntities } from "@/lib/bannerSlice";
import { useAuthSession } from "@/providers/AuthProvider"; import { useAuthSession } from "@/providers/AuthProvider";
import { Entypo } from "@expo/vector-icons"; import { Entypo } from "@expo/vector-icons";
import * as ImagePicker from 'expo-image-picker'; import * as ImagePicker from "expo-image-picker";
import { router, Stack } from "expo-router"; import { router, Stack } from "expo-router";
import { useState } from "react"; import { useState } from "react";
import { Image, Platform, Pressable, SafeAreaView, ScrollView, Text, View } from "react-native"; import {
Image,
Pressable,
SafeAreaView,
ScrollView,
Text,
ToastAndroid,
View,
} from "react-native";
import { useDispatch } from "react-redux"; import { useDispatch } from "react-redux";
import * as FileSystem from 'expo-file-system';
import axios from "axios";
import ReactNativeBlobUtil from 'react-native-blob-util';
import { launchImageLibrary } from "react-native-image-picker";
const debug = true
export default function CreateBanner() { export default function CreateBanner() {
const { decryptToken, token } = useAuthSession() const { decryptToken, token } = useAuthSession();
const dispatch = useDispatch() const dispatch = useDispatch();
const [selectedImage, setSelectedImage] = useState<string | undefined>(undefined) const [selectedImage, setSelectedImage] = useState<string | undefined>(
const [imgForm, setImgForm] = useState<any>() undefined
const [title, setTitle] = useState('') );
const [imgForm, setImgForm] = useState<any>();
const [title, setTitle] = useState("");
const [error, setError] = useState(false);
const pickImageAsync = async () => { const pickImageAsync = async () => {
kirim()
return
let result = await ImagePicker.launchImageLibraryAsync({ let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ['images'], mediaTypes: ["images"],
allowsEditing: false, allowsEditing: true,
quality: 1, quality: 1,
aspect: [1535, 450],
}); });
const formData = new FormData()
formData.append('file', result.assets![0].uri)
if (debug) console.log("[mengirim gambar]")
const res = await fetch("http://10.0.2.2:3000/api/v2/test", {
method: "POST",
body: formData,
});
console.log("[res]", await res.json())
if (debug) console.log("[pickImageAsync]")
if (!result.canceled) { if (!result.canceled) {
if (result.assets?.[0].uri) { if (result.assets?.[0].uri) {
// setSelectedImage(result.assets[0].uri); setSelectedImage(result.assets[0].uri);
// setImgForm(result.assets[0]) setImgForm(result.assets[0]);
const formData = new FormData()
formData.append('file', result.assets[0].uri)
if (debug) console.log("[mengirim gambar]")
const res = await fetch("http://10.0.2.2:3000/api/v2/test", {
method: "POST",
body: formData,
});
console.log("[res]", await res.json())
} else { } else {
if (debug) console.log("[pickImageAsync]", 'Tidak ada gambar yang dipilih'); alert("Tidak ada gambar yang dipilih");
alert('Tidak ada gambar yang dipilih');
} }
console.log("[imgForm]", imgForm)
} else {
if (debug) console.log("[pickImageAsync]", 'Tidak ada gambar yang dipilih');
alert('Tidak ada gambar yang dipilih');
} }
}; };
function onValidate(val: string) {
setTitle(val)
if (val == "") {
setError(true);
} else {
setError(false);
}
}
const handleCreateEntity = async () => { const handleCreateEntity = async () => {
// const hasil = await decryptToken(String(token?.current)) const hasil = await decryptToken(String(token?.current));
// const fd = new FormData() const fd = new FormData();
fd.append("file", {
uri: imgForm.uri,
type: imgForm.mimeType,
name: imgForm.fileName,
} as any);
// fd.append("file", JSON.stringify({ fd.append(
// uri: imgForm.uri, "data",
// type: imgForm.mimeType, JSON.stringify({
// name: imgForm.fileName, title,
// size: imgForm.fileSize, user: hasil,
// })) })
// fd.append("data", JSON.stringify( );
// {
// title: title, const createdEntity = await apiCreateBanner(fd);
// user: hasil if (createdEntity.success) {
// } ToastAndroid.show("Berhasil menambahkan data", ToastAndroid.SHORT);
// )) apiGetBanner({ user: hasil }).then((data) =>
// const createdEntity = await apiCreateBanner(fd); dispatch(setEntities(data.data))
// console.log("[createdEntity]", createdEntity) );
// dispatch(addEntity(createdEntity)); router.back();
} else {
ToastAndroid.show('Gagal menambahkan data', ToastAndroid.SHORT);
}
}; };
return ( return (
<SafeAreaView> <SafeAreaView>
<Stack.Screen <Stack.Screen
options={{ options={{
headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />, headerLeft: () => (
headerTitle: 'Tambah Banner', <ButtonBackHeader
headerTitleAlign: 'center', onPress={() => {
headerRight: () => <ButtonSaveHeader category="create" onPress={() => { handleCreateEntity() }} /> router.back();
}}
/>
),
headerTitle: "Tambah Banner",
headerTitleAlign: "center",
headerRight: () => (
<ButtonSaveHeader
disable={title == "" || selectedImage == undefined || error ? true : false}
category="create"
onPress={() => {
handleCreateEntity();
}}
/>
),
}} }}
/> />
<ScrollView> <ScrollView>
<View style={[Styles.p15, Styles.mb100]}> <View style={[Styles.p15, Styles.mb100]}>
<View style={[Styles.mb15]}> <View style={[Styles.mb15]}>
{ {selectedImage != undefined ? (
selectedImage != undefined ? ( <Pressable onPress={pickImageAsync}>
<Pressable onPress={pickImageAsync}> <Image
<Image src={selectedImage} style={{ resizeMode: 'contain', width: '100%', height: 100 }} /> src={selectedImage}
</Pressable> style={{ resizeMode: "contain", width: "100%", height: 100 }}
) : ( />
<Pressable onPress={pickImageAsync} style={[Styles.wrapPaper, Styles.contentItemCenter]}> </Pressable>
<View style={{ justifyContent: 'center', alignItems: 'center' }}> ) : (
<Entypo name="image" size={50} color={'#aeaeae'} /> <Pressable
<Text style={[Styles.textInformation, Styles.mt05]}>Mohon unggah gambar dalam resolusi 1535 x 450 pixel untuk memastikan</Text> onPress={pickImageAsync}
</View> style={[Styles.wrapPaper, Styles.contentItemCenter]}
</Pressable> >
) <View
} style={{ justifyContent: "center", alignItems: "center" }}
>
<Entypo name="image" size={50} color={"#aeaeae"} />
<Text style={[Styles.textInformation, Styles.mt05]}>
Mohon unggah gambar dalam resolusi 1535 x 450 pixel untuk
memastikan
</Text>
</View>
</Pressable>
)}
</View> </View>
<InputForm label="Judul" type="default" placeholder="Judul" required bg="white" onChange={setTitle} /> <InputForm
label="Judul"
type="default"
placeholder="Judul"
required
bg="white"
onChange={onValidate}
error={error}
errorText="Judul harus diisi"
/>
</View> </View>
</ScrollView> </ScrollView>
</SafeAreaView> </SafeAreaView>
) );
} }
const requestPermission = async () => {
if (Platform.OS !== 'web') {
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted') {
alert('Maaf, kami membutuhkan izin untuk mengakses galeri!');
return false;
}
return true;
}
return true;
};
const base64ToBlob = (base64: string, mimeType: string) => {
const byteString = atob(base64);
const arrayBuffer = new ArrayBuffer(byteString.length);
const int8Array = new Uint8Array(arrayBuffer);
for (let i = 0; i < byteString.length; i++) {
int8Array[i] = byteString.charCodeAt(i);
}
return new Blob([int8Array], { type: mimeType });
};
async function kirim() {
console.log("clicked");
const result = await launchImageLibrary({
mediaType: "photo",
quality: 1,
includeBase64: true,
});
if (!result.assets || result.assets.length === 0) {
console.log("No image selected");
return;
}
const base64 = result.assets[0].base64!;
const mimeType = result.assets[0].type!; // e.g., 'image/jpeg'
const blob = base64ToBlob(base64, mimeType);
const formData = new FormData();
formData.append("file", blob);
formData.append("name", "bip.png");
const res = await fetch("http://10.0.2.2:3000/api/v2/test", {
method: "POST",
body: formData,
});
console.log(await res.text());
}

View File

@@ -5,17 +5,42 @@ import ButtonBackHeader from "@/components/buttonBackHeader"
import DrawerBottom from "@/components/drawerBottom" import DrawerBottom from "@/components/drawerBottom"
import MenuItemRow from "@/components/menuItemRow" import MenuItemRow from "@/components/menuItemRow"
import Styles from "@/constants/Styles" import Styles from "@/constants/Styles"
import { apiDeleteBanner, apiGetBanner } from "@/lib/api"
import { setEntities } from "@/lib/bannerSlice"
import { useAuthSession } from "@/providers/AuthProvider"
import { Ionicons, MaterialCommunityIcons } from "@expo/vector-icons" import { Ionicons, MaterialCommunityIcons } from "@expo/vector-icons"
import { router, Stack } from "expo-router" import { router, Stack } from "expo-router"
import { useState } from "react" import { useState } from "react"
import { Image, SafeAreaView, ScrollView, ToastAndroid, View } from "react-native" import { Image, SafeAreaView, ScrollView, ToastAndroid, View } from "react-native"
import { useSelector } from "react-redux" import { useDispatch, useSelector } from "react-redux"
export default function BannerList() { export default function BannerList() {
const { decryptToken, token } = useAuthSession();
const [isModal, setModal] = useState(false) const [isModal, setModal] = useState(false)
const entities = useSelector((state: any) => state.banner) const entities = useSelector((state: any) => state.banner)
const [dataId, setDataId] = useState('') const [dataId, setDataId] = useState('')
const [dataStorage, setDataStorage] = useState('') const dispatch = useDispatch();
const handleDeleteEntity = async () => {
try {
const hasil = await decryptToken(String(token?.current));
const deletedEntity = await apiDeleteBanner({ user: hasil }, dataId);
if (deletedEntity.success) {
ToastAndroid.show("Berhasil menghapus data", ToastAndroid.SHORT);
apiGetBanner({ user: hasil }).then((data) =>
dispatch(setEntities(data.data))
);
} else {
ToastAndroid.show('Gagal menghapus data', ToastAndroid.SHORT);
}
} catch (error) {
console.error(error)
ToastAndroid.show('Terjadi kesalahan', ToastAndroid.SHORT)
} finally {
setModal(false)
}
};
return ( return (
<SafeAreaView> <SafeAreaView>
@@ -35,7 +60,6 @@ export default function BannerList() {
key={key} key={key}
onPress={() => { onPress={() => {
setDataId(index.id) setDataId(index.id)
setDataStorage(index.image)
setModal(true) setModal(true)
}} }}
borderType="all" borderType="all"
@@ -73,10 +97,7 @@ export default function BannerList() {
AlertKonfirmasi({ AlertKonfirmasi({
title: 'Konfirmasi', title: 'Konfirmasi',
desc: 'Apakah anda yakin ingin menghapus data?', desc: 'Apakah anda yakin ingin menghapus data?',
onPress: () => { onPress: () => { handleDeleteEntity() }
setModal(false)
ToastAndroid.show('Berhasil menghapus data', ToastAndroid.SHORT)
}
}) })
}} }}
/> />

View File

@@ -2,40 +2,16 @@ import Styles from "@/constants/Styles"
import { apiCheckPhoneLogin, apiSendOtp } from "@/lib/api" import { apiCheckPhoneLogin, apiSendOtp } from "@/lib/api"
import AsyncStorage from "@react-native-async-storage/async-storage" import AsyncStorage from "@react-native-async-storage/async-storage"
import { useState } from "react" import { useState } from "react"
import { Button, Image, Text, ToastAndroid, View } from "react-native" import { Image, Text, ToastAndroid, View } from "react-native"
import { ButtonForm } from "../buttonForm" import { ButtonForm } from "../buttonForm"
import { InputForm } from "../inputForm" import { InputForm } from "../inputForm"
import ModalLoading from "../modalLoading" import ModalLoading from "../modalLoading"
import * as ImagePicker from 'expo-image-picker';
type Props = { type Props = {
onValidate: ({ phone, otp }: { phone: string, otp: number }) => void onValidate: ({ phone, otp }: { phone: string, otp: number }) => void
} }
async function handleUpload() {
console.log('handleUpload')
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: false,
aspect: [4, 3],
quality: 1,
});
const formData = new FormData()
formData.append('file', {
uri: result.assets![0].uri,
type: "image/jpeg",
name: "bip.png",
} as any)
const res = await fetch("https://amal.wibudev.com/api/v2/test", {
method: "POST",
body: formData,
});
console.log(await res.json())
}
export default function ViewLogin({ onValidate }: Props) { export default function ViewLogin({ onValidate }: Props) {
const [loadingLogin, setLoadingLogin] = useState(false) const [loadingLogin, setLoadingLogin] = useState(false)
const [disableLogin, setDisableLogin] = useState(true) const [disableLogin, setDisableLogin] = useState(true)
@@ -66,7 +42,6 @@ export default function ViewLogin({ onValidate }: Props) {
return ( return (
<> <>
<View style={Styles.wrapLogin} > <View style={Styles.wrapLogin} >
<Button title="Upload" onPress={handleUpload} />
<View style={{ alignItems: "center", marginVertical: 50 }}> <View style={{ alignItems: "center", marginVertical: 50 }}>
<Image <Image
source={require("../../assets/images/splash-icon.png")} source={require("../../assets/images/splash-icon.png")}

View File

@@ -30,16 +30,39 @@ export const apiGetBanner = async ({ user }: { user: string }) => {
return response.data; return response.data;
}; };
export const apiCreateBanner = async (data: FormData) => { export const apiCreateBanner = async (data: FormData) => {
const response = await api.post('mobile/banner', data, { const response = await api.post('mobile/banner', data,
headers: { {
'Content-Type': 'multipart/form-data', headers: {
}, 'Content-Type': 'multipart/form-data',
}) },
}
)
return response.data; return response.data;
}; };
export const apiDeleteBanner = async (data: { user: string }, id: string) => {
const response = await api.delete(`mobile/banner/${id}`, { data })
return response.data;
};
export const apiGetBannerOne = async ({ user, id }: { user: string, id: string }) => {
const response = await api.get(`mobile/banner/${id}?user=${user}`);
return response.data;
};
export const apiEditBanner = async (data: FormData, id: string) => {
const response = await api.put(`mobile/banner/${id}`, data,
{
headers: {
'Content-Type': 'multipart/form-data',
},
}
)
return response.data;
};
export const apiGetDataHome = async ({ cat, user }: { cat: 'kegiatan' | 'division' | 'progress' | 'dokumen' | 'event' | 'discussion' | 'header' | 'check-late-project', user: string }) => { export const apiGetDataHome = async ({ cat, user }: { cat: 'kegiatan' | 'division' | 'progress' | 'dokumen' | 'event' | 'discussion' | 'header' | 'check-late-project', user: string }) => {
const response = await api.get(`mobile/home?user=${user}&cat=${cat}`); const response = await api.get(`mobile/home?user=${user}&cat=${cat}`);
return response.data; return response.data;