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

@@ -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());
}