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 ButtonSaveHeader from "@/components/buttonSaveHeader"
import { InputForm } from "@/components/inputForm"
import Styles from "@/constants/Styles"
import { Entypo } from "@expo/vector-icons"
import * as ImagePicker from 'expo-image-picker'
import { router, Stack } from "expo-router"
import { useState } from "react"
import { Image, Pressable, SafeAreaView, ScrollView, Text, View } from "react-native"
import ButtonBackHeader from "@/components/buttonBackHeader";
import ButtonSaveHeader from "@/components/buttonSaveHeader";
import { InputForm } from "@/components/inputForm";
import Styles from "@/constants/Styles";
import { apiEditBanner, apiGetBanner, apiGetBannerOne } from "@/lib/api";
import { setEntities } from "@/lib/bannerSlice";
import { useAuthSession } from "@/providers/AuthProvider";
import { Entypo } from "@expo/vector-icons";
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() {
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 () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ['images'],
allowsEditing: false,
mediaTypes: ["images"],
allowsEditing: true,
quality: 1,
aspect: [1535, 450],
});
if (!result.canceled) {
setSelectedImage(result.assets[0].uri);
setImgForm(result.assets[0]);
} 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>
<Stack.Screen
options={{
headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
headerTitle: 'Edit Banner',
headerTitleAlign: 'center',
headerRight: () => <ButtonSaveHeader category="update" />
headerLeft: () => (
<ButtonBackHeader
onPress={() => {
router.back();
}}
/>
),
headerTitle: "Edit Banner",
headerTitleAlign: "center",
headerRight: () => <ButtonSaveHeader
disable={title == "" || error ? true : false}
onPress={() => { handleUpdateEntity() }}
category="update" />,
}}
/>
<ScrollView>
<View style={[Styles.p15, Styles.mb100]}>
<View style={[Styles.mb15]}>
{
selectedImage != undefined ? (
<Pressable onPress={pickImageAsync}>
<Image src={selectedImage} style={{ resizeMode: 'contain', width: '100%', height: 100 }} />
</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>
)
}
{selectedImage != undefined ? (
<Pressable onPress={pickImageAsync}>
<Image
src={
typeof selectedImage === "string"
? selectedImage
: selectedImage.uri
}
style={{ resizeMode: "contain", width: "100%", height: 100 }}
/>
</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>
<InputForm label="Judul" type="numeric" placeholder="Judul" required bg="white" />
{/* <ButtonForm
text="SIMPAN"
onPress={() => {
AlertKonfirmasi({
title: 'Konfirmasi',
desc: 'Apakah anda yakin ingin mengubah data?',
onPress: () => {
ToastAndroid.show('Berhasil mengubah data', ToastAndroid.SHORT)
router.push('/banner')
}
})
}} /> */}
<InputForm
label="Judul"
type="default"
placeholder="Judul"
required
bg="white"
value={title}
error={error}
onChange={onValidate}
errorText="Judul tidak boleh kosong"
/>
</View>
</ScrollView>
</SafeAreaView>
)
}
);
}

View File

@@ -2,195 +2,153 @@ import ButtonBackHeader from "@/components/buttonBackHeader";
import ButtonSaveHeader from "@/components/buttonSaveHeader";
import { InputForm } from "@/components/inputForm";
import Styles from "@/constants/Styles";
import { apiCreateBanner } from "@/lib/api";
import { addEntity } from "@/lib/bannerSlice";
import { apiCreateBanner, apiGetBanner } from "@/lib/api";
import { setEntities } from "@/lib/bannerSlice";
import { useAuthSession } from "@/providers/AuthProvider";
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 { 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 * 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() {
const { decryptToken, token } = useAuthSession()
const dispatch = useDispatch()
const [selectedImage, setSelectedImage] = useState<string | undefined>(undefined)
const [imgForm, setImgForm] = useState<any>()
const [title, setTitle] = useState('')
const { decryptToken, token } = useAuthSession();
const dispatch = useDispatch();
const [selectedImage, setSelectedImage] = useState<string | undefined>(
undefined
);
const [imgForm, setImgForm] = useState<any>();
const [title, setTitle] = useState("");
const [error, setError] = useState(false);
const pickImageAsync = async () => {
kirim()
return
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ['images'],
allowsEditing: false,
mediaTypes: ["images"],
allowsEditing: true,
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.assets?.[0].uri) {
// setSelectedImage(result.assets[0].uri);
// 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())
setSelectedImage(result.assets[0].uri);
setImgForm(result.assets[0]);
} 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 hasil = await decryptToken(String(token?.current))
// const fd = new FormData()
const hasil = await decryptToken(String(token?.current));
const fd = new FormData();
fd.append("file", {
uri: imgForm.uri,
type: imgForm.mimeType,
name: imgForm.fileName,
} as any);
// fd.append("file", JSON.stringify({
// uri: imgForm.uri,
// type: imgForm.mimeType,
// name: imgForm.fileName,
// size: imgForm.fileSize,
// }))
// fd.append("data", JSON.stringify(
// {
// title: title,
// user: hasil
// }
// ))
// const createdEntity = await apiCreateBanner(fd);
// console.log("[createdEntity]", createdEntity)
// dispatch(addEntity(createdEntity));
fd.append(
"data",
JSON.stringify({
title,
user: hasil,
})
);
const createdEntity = await apiCreateBanner(fd);
if (createdEntity.success) {
ToastAndroid.show("Berhasil menambahkan data", ToastAndroid.SHORT);
apiGetBanner({ user: hasil }).then((data) =>
dispatch(setEntities(data.data))
);
router.back();
} else {
ToastAndroid.show('Gagal menambahkan data', ToastAndroid.SHORT);
}
};
return (
<SafeAreaView>
<Stack.Screen
options={{
headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
headerTitle: 'Tambah Banner',
headerTitleAlign: 'center',
headerRight: () => <ButtonSaveHeader category="create" onPress={() => { handleCreateEntity() }} />
headerLeft: () => (
<ButtonBackHeader
onPress={() => {
router.back();
}}
/>
),
headerTitle: "Tambah Banner",
headerTitleAlign: "center",
headerRight: () => (
<ButtonSaveHeader
disable={title == "" || selectedImage == undefined || error ? true : false}
category="create"
onPress={() => {
handleCreateEntity();
}}
/>
),
}}
/>
<ScrollView>
<View style={[Styles.p15, Styles.mb100]}>
<View style={[Styles.mb15]}>
{
selectedImage != undefined ? (
<Pressable onPress={pickImageAsync}>
<Image src={selectedImage} style={{ resizeMode: 'contain', width: '100%', height: 100 }} />
</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 pixel untuk memastikan</Text>
</View>
</Pressable>
)
}
{selectedImage != undefined ? (
<Pressable onPress={pickImageAsync}>
<Image
src={selectedImage}
style={{ resizeMode: "contain", width: "100%", height: 100 }}
/>
</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 pixel untuk
memastikan
</Text>
</View>
</Pressable>
)}
</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>
</ScrollView>
</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 MenuItemRow from "@/components/menuItemRow"
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 { router, Stack } from "expo-router"
import { useState } from "react"
import { Image, SafeAreaView, ScrollView, ToastAndroid, View } from "react-native"
import { useSelector } from "react-redux"
import { useDispatch, useSelector } from "react-redux"
export default function BannerList() {
const { decryptToken, token } = useAuthSession();
const [isModal, setModal] = useState(false)
const entities = useSelector((state: any) => state.banner)
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 (
<SafeAreaView>
@@ -35,7 +60,6 @@ export default function BannerList() {
key={key}
onPress={() => {
setDataId(index.id)
setDataStorage(index.image)
setModal(true)
}}
borderType="all"
@@ -73,10 +97,7 @@ export default function BannerList() {
AlertKonfirmasi({
title: 'Konfirmasi',
desc: 'Apakah anda yakin ingin menghapus data?',
onPress: () => {
setModal(false)
ToastAndroid.show('Berhasil menghapus data', ToastAndroid.SHORT)
}
onPress: () => { handleDeleteEntity() }
})
}}
/>

View File

@@ -2,40 +2,16 @@ import Styles from "@/constants/Styles"
import { apiCheckPhoneLogin, apiSendOtp } from "@/lib/api"
import AsyncStorage from "@react-native-async-storage/async-storage"
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 { InputForm } from "../inputForm"
import ModalLoading from "../modalLoading"
import * as ImagePicker from 'expo-image-picker';
type Props = {
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) {
const [loadingLogin, setLoadingLogin] = useState(false)
const [disableLogin, setDisableLogin] = useState(true)
@@ -66,7 +42,6 @@ export default function ViewLogin({ onValidate }: Props) {
return (
<>
<View style={Styles.wrapLogin} >
<Button title="Upload" onPress={handleUpload} />
<View style={{ alignItems: "center", marginVertical: 50 }}>
<Image
source={require("../../assets/images/splash-icon.png")}

View File

@@ -30,16 +30,39 @@ export const apiGetBanner = async ({ user }: { user: string }) => {
return response.data;
};
export const apiCreateBanner = async (data: FormData) => {
const response = await api.post('mobile/banner', data, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
const response = await api.post('mobile/banner', data,
{
headers: {
'Content-Type': 'multipart/form-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 }) => {
const response = await api.get(`mobile/home?user=${user}&cat=${cat}`);
return response.data;