How to fix React Native code to show two different flatlist (Json Api) in one screen and can use search feature - json

I want to create an application screen, in that screen it can show 2 flatlists from different api, I call it using a button.
For that process I was successful, but I want to add a search feature by reading every list that is called or active at that time, but this doesn't work. And if I take it also does not work. In this flatlist I also want to be able to move the detail pages.
This is for my college semester assignment.
import {
Box,
Text,
Image,
Heading,
Center,
ScrollView,
Spinner,
FlatList,
Pressable,
View,
HStack,
Button,
} from 'native-base';
import React, { Component } from 'react';
import { Dimensions, TouchableOpacity, StatusBar } from 'react-native';
import {LinearGradient} from 'expo-linear-gradient';
import { Ionicons, Entypo } from '#expo/vector-icons';
import { ListItem, SearchBar } from '#rneui/themed';
const windowWidth = Dimensions.get('window').width;
class Legal extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
isLoading: true,
categories: ['apps', 'products'],
contentSwitcher: false,
isFetching: false,
searchTxt: null,
error: null,
temp: [],
};
}
async getApps() {
try {
const response = await fetch(
'https://ojk-invest-api.vercel.app/api/apps'
);
const json = await response.json();
this.setState({ data: json.data.apps });
} catch (error) {
console.error(error);
} finally {
this.setState({ isLoading: false, contentSwitcher: false });
}
}
async getProducts() {
try {
const response = await fetch(
'https://ojk-invest-api.vercel.app/api/products'
);
const json = await response.json();
this.setState({ data: json.data.products, contentSwitcher: true });
} catch (error) {
console.error(error);
} finally {
this.setState({ isLoading: false });
}
}
setResult = (res) => {
this.setState ({
data: [...this.state.data, ...res.data.apps],
temp: [...this.state.temp, ...res.data.apps],
error: res.error || null,
isLoading: false,
});
};
renderHeader = () => {
return <SearchBar placeholder='Cari ...'
lightTheme round editable={true}
value={this.state.searchTxt}
onChangeText={this.updateSearch}
/>
};
updateSearch = searchTxt => {
this.setState({searchTxt}, () => {
if ('' == searchTxt) {
this.setState({
data: [...this.state.temp],
});
return;
}
this.state.data = this.state.temp.filter(function (item) {
return item.name.includes(searchTxt);
}).map(function({ id, name, type }) {
return {id, name, type};
});
});
};
componentDidMount() {
this.getApps();
}
onRefresh = () => {
this.setState({ isFetching: true }, () => {
this.getApps();
});
};
renderItem = ({ item }) => {
const { navigation } = this.props;
return (
<>
<Pressable
style={{ padding: 20, backgroundColor: 'white' }}
onPress={() => navigation.navigate('Detail Produk', { data: item })}>
<Center>
<View
style={{
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
}}>
<Text
style={{
fontSize: 16,
width: windowWidth - 40,
textAlign: 'justify',
marginTop: 6,
}}>
{item.name}
</Text>
<Text
style={{
color: '#808080',
fontSize: 14,
width: windowWidth - 40,
textAlign: 'justify',
marginTop: 6,
}}>
{this.state.contentSwitcher ? item.management : item.owner}
</Text>
</View>
</Center>
</Pressable>
<View style={{ borderWidth: 0.5, borderColor: '#cccccc' }}></View>
</>
);
};
render() {
const { data, isLoading, isFetching } = this.state;
return (
<View style={{ flex: 1, justifyContent: 'center'}}>
<HStack alignItems="center" bgColor="#fff" p="1" w={window.width}>
<Pressable m="2" rounded="8" p="2" flex={1} textAlign="center">
<Button onPress={() => this.getApps()}
leftIcon={<Ionicons name="folder" color="white" />}
colorScheme="green"
>
Aplikasi
</Button>
</Pressable>
<Pressable m="2" rounded="8" p="2" flex={1} textAlign="center">
<Button onPress={() => this.getProducts()}
leftIcon={<Entypo name="box" color="white" />}
colorScheme="green"
>
Produk
</Button>
</Pressable>
</HStack>
{isLoading ? (
<Spinner size="large" color="#AA0002" />
) : (
<FlatList
ListHeaderComponent={this.renderHeader}
data={data}
keyExtractor={({ link }, index) => link}
renderItem={this.renderItem}
onRefresh={this.onRefresh}
refreshing={isFetching}
/>
)}
</View>
);
}
}
export default Legal;

Related

Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method. in my app

i tried to show search result feature by using flatlist (json API) and search bar in my code, but i found this error and can't solve it. I can run the search but can't display the search results, can anyone help me solve this error, because this is for my college assignment
this is my code
import {
Box,
Text,
Image,
Heading,
Center,
ScrollView,
Spinner,
FlatList,
Pressable,
View,
Stack,
} from 'native-base';
import React, { Component } from 'react';
import { Dimensions } from 'react-native';
import { ListItem, SearchBar } from '#rneui/themed';
const windowWidth = Dimensions.get('window').width;
class Ilegal extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
isLoading: true,
isFetching: false,
searchTxt: null,
error: null,
temp: [],
};
};
async getData() {
try {
const response = await fetch(
'https://ojk-invest-api.vercel.app/api/illegals'
);
const json = await response.json();
this.setState({ data: json.data.illegals });
this.setResult(json);
} catch (error) {
console.error(error);
} finally {
this.setState({
isLoading: false,
isFetching: false,
});
}
};
setResult = (res) => {
this.setState ({
data: [...this.state.data, ...res],
temp: [...this.state.temp, ...res],
error: res.error || null,
isLoading: false,
});
};
renderHeader = () => {
return <SearchBar placeholder='Cari Perusahaan..'
lightTheme round editable={true}
value={this.state.searchTxt}
onChangeText={this.updateSearch}
/>
};
updateSearch = searchTxt => {
this.setState({searchTxt}, () => {
if ('' == searchTxt) {
this.setState({
data: [...this.state.temp],
});
return;
}
this.state.data = this.state.temp.filter(function (item) {
return item.name.includes(searchTxt);
}).map(function({ id, name, type }) {
return {id, name, type};
});
});
};
componentDidMount() {
this.getData();
};
onRefresh = () => {
this.setState({ isFetching: true }, () => {
this.getData();
});
};
renderItem = ({ item }) => {
const { navigation } = this.props;
return (
<>
<Pressable
style={{ padding: 20, backgroundColor: 'white' }}
onPress={() => navigation.navigate('Detail Ilegal', { data: item })}>
<Center>
<View
style={{
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
}}>
<Text
style={{
fontSize: 16,
width: windowWidth - 40,
textAlign: 'justify',
marginTop: 6,
}}>
{item.name}
</Text>
<Text
style={{
color: '#808080',
fontSize: 14,
width: windowWidth - 40,
textAlign: 'justify',
marginTop: 6,
}}>
{item.type}
</Text>
</View>
</Center>
</Pressable>
<View style={{ borderWidth: 0.5, borderColor: '#cccccc' }}></View>
</>
);
};
render() {
const { data, isLoading, isFetching, error} = this.state;
return (
<View style={{ flex:1, justifyContent:'center', backgroundColor:'white', flexDirection: 'column', }}>
{isLoading ? (
<Spinner size="large" color="#AA0002" />
) : (
<FlatList
ListHeaderComponent={this.renderHeader}
data={data}
keyExtractor={({ link }, index) => link}
renderItem={this.renderItem}
onRefresh={this.onRefresh}
refreshing={isFetching}
/>
)}
</View>
);
}
}
export default Ilegal;
you can help me for fixed this error ?
I think the error is in setResult() function as far as I could understood your set result function. You are setting data like this
this.setState({ data: json.data.illegals });
in getData() while you are fetching data from API but you are sending json as parameter to setResult which is object. Try to change your setResult() as below:
setResult = (res) => {
this.setState ({
data: [...this.state.data, ...res.data.illegals],
temp: [...this.state.temp, ...res.data.illegals],
error: res.error || null,
isLoading: false,
});
};

show a list of data in react native app from sql server

I wanted to show a list of data in my app, I already have backend API that can get the data from the server but when I trying to make it appear in my react native app, it wont appear. Below is the data that get from API
here is the code for show the data in a list view in react native apps
import React, { useState, useEffect,Component,onMount} from 'react';
import {View,Text, Button, StyleSheet,TextInput,ListView,ActivityIndicator,Platform} from 'react-native';
import {useNavigation} from'#react-navigation/native';
import {StatusBar} from'expo-status-bar';
export default function StopJob(){
const[isLoading,setIsLoading]=useState(true);
useEffect(()=>{
return fetch('http://localhost/api/findid.php',{
mode:'no-cors'
})
.then((response) => response.json())
.then((responseJson) => {
let ds = new ListView.DataSource({rowHasChanged: (r1, r2)=> r1 !== r2});
this.setState({
isLoading: false,
dataSource: ds.cloneWithRows(responseJson),
}, function() {
// In this block you can do something with new state.
});
})
.catch((error) => {
console.error(error);
})
},[]);
const Showlist=(user,job,jobid,machinecode,startTime)=>{
this.props.navigation.navigate('Third', {
Userid : user,
Job : job,
JobId : jobid,
MachineCode : machinecode,
StartTime : startTime
});
}
const ListViewItemSeparator = () => {
return (
<View
style={{
height: .5,
width: "100%",
backgroundColor: "#000",
}}
/>
);
}
if(isLoading)return(<View style={{flex: 1, paddingTop: 20}}><ActivityIndicator /> </View>);
return(
<View style={styles.MainContainer_For_Show_StudentList_Activity}>
<ListView
dataSource={this.state.dataSource}
renderSeparator= {this.ListViewItemSeparator}
renderRow={ (rowData) => <Text style={styles.rowViewContainer}
onPress={this.Showlist.bind(
this, rowData.user,
rowData.job,
rowData.jobid,
rowData.machinecode,
rowData.startTime
)} >
{rowData.job}
</Text> }
/>
</View>
);
}
const styles = StyleSheet.create({
MainContainer_For_Show_StudentList_Activity :{
flex:1,
paddingTop: (Platform.OS == 'ios') ? 20 : 0,
marginLeft: 5,
marginRight: 5
},
rowViewContainer: {
fontSize: 20,
paddingRight: 10,
paddingTop: 10,
paddingBottom: 10,
}
});
the expected output will only show the job from the database, but for now the function did not show the list view the error shown Text strings must be rendered within a component.
I was referring this webpage to implement the code : https://reactnativecode.com/insert-update-display-delete-crud-operations/
on the example it show function well but when I try to implement it, it cant work :(
updated but still having same error
export default function StopJob(){
const[isLoading,setIsLoading]=useState(true);
const[dataSource,setdataSource]=useState();
useEffect(()=>{
return fetch('http://localhost/api/findid.php')
.then((response) => response.json())
.then((responseJson) => {
let ds = new FlatList.DataSource({rowHasChanged: (r1, r2)=> r1 !== r2});
setIsLoading(false)
setdataSource(ds.cloneWithRows(responseJson))
})
.catch((error) => {
console.error(error);
})
},[]);
const Showlist=(user,job,jobid,machinecode,startTime)=>{
this.props.navigation.navigate('', {
Userid : user,
Job : job,
JobId : jobid,
MachineCode : machinecode,
StartTime : startTime
});
}
const ListViewItemSeparator = () => {
return (
<View
style={{
height: .5,
width: "100%",
backgroundColor: "#000",
}}
/>
);
}
if(isLoading)return(<View style={{flex: 1, paddingTop: 20}}><ActivityIndicator /> </View>);
return(
<View style={styles.MainContainer_For_Show_StudentList_Activity}>
<FlatList
dataSource={dataSource}
keyExtractor={item=>item.user}
ItemSeparatorComponent= {ListViewItemSeparator()}
renderItem={ (item) => <Text style={styles.rowViewContainer}>{item.job}</Text> }
/>
</View>
);
}
Ok here are the steps to follow:
Use flatlist
Your data source should be a regular array. So, you can use the response from your api as it is.
renderRow should change as renderItem
renderSeparator should change as ItemSeparatorComponent
here is the final form:
const[isLoading,setIsLoading]=useState(true);
const [data, setData]=useState([]);
.......
fetch('http://localhost/api/findid.php',{
mode:'no-cors'
})
.then((response) => response.json())
.then((responseJson) => {
//you can't use setState inside function components. :)
setData(responseJson);
setLoading(false);
})
.catch((error) => {
console.error(error);
})
.......
<FlatList
data={data}
keyExtractor={item => item.jobid} //it should be unique. change it
renderItem={({item}) => <Text>{item.job}</Text>}
/>
This should solve your issue for now but keep in mind these too:
Looks like you don't know differences between class components and function components. Do your research
Flatlist has it's own performance configurations. Research and implement them.

I have this issue undefined is not an object (evaluating 'this.state.dataSource.map')

I want to display a list of places from a online json url.
import React, { Component } from "react";
import {
View,
StyleSheet,
Dimensions,
Image,
StatusBar,
TextInput,
TouchableOpacity,
Text,
Button,
Platform,
Alert,
FlatList,
ActivityIndicator,
} from "react-native";
let url = "https://cz2006api.herokuapp.com/api/getAll";
let url2 = "";
export default class ClinicComponent extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: null,
};
}
componentDidMount() {
return fetch("https://cz2006api.herokuapp.com/api/getAll")
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.data.data,
});
})
.catch((error) => {
console.log(error);
});
}
render() {
if (this.state.isLoading) {
return (
<View style={styles.container}>
<ActivityIndicator />
</View>
);
} else {
let hospitals = this.state.dataSource.map((val, key) => {
return (
<View key={key} style={styles.item}>
<Text>{val.name}</Text>
</View>
);
});
return (
<View style={styles.item}>
{/* <Text>Content Loaded</Text> */}
{hospitals}
</View>
);
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
item: {
flex: 1,
alignSelf: "stretch",
margin: 10,
alignItems: "center",
justifyContent: "center",
borderBottomWidth: 1,
borderBottomColor: "#eee",
},
});
Unfortunately when i tried to run this via expo cli I got an error, saying undefined is not an object
enter image description here
Can anyone help me pls!!! I would just like to have a list of hospitals which are scrollable. Thank you!
The URL of the Json is here: https://cz2006api.herokuapp.com/api/getAll
Simply change your initial state to something like this
this.state = {
isLoading: true,
dataSource: [], // <-- here
};
Your problem is you're using dataSource.map but during api calling your dataSource still stay null until it get its response, and null object have no attribute map. That's the cause of your problem.
remove the return in componentDidMount:
componentDidMount() {
fetch("https://cz2006api.herokuapp.com/api/getAll")
.then((response) => response.json())
.then((responseJson) => {
this.setState({
dataSource: responseJson.data.data,
isLoading: false,
});
})
.catch((error) => {
console.log(error);
});
}
I agree with #Nguyễn's suggestion that your initial state should be an array. However the root of the issue seems to be getting the right properties off off your JSON response.
First, you want responseJson.data instead of responseJson.data.data. That gives me an array and shows a long list but the titles are all blank. That's because your response has Name as an uppercase property but you are accessing name. So you need to change that as well.
export default class ClinicComponent extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: [],
};
}
componentDidMount() {
return fetch('https://cz2006api.herokuapp.com/api/getAll')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.data,
});
})
.catch((error) => {
console.log(error);
});
}
render() {
//console.log(this.state.dataSource?.[0]);
if (this.state.isLoading) {
return (
<View style={styles.container}>
<ActivityIndicator />
</View>
);
} else {
return (
<View style={styles.item}>
{/* <Text>Content Loaded</Text> */}
{this.state.dataSource.map((val, key) => (
<View key={val._id} style={styles.item}>
<Text>{val.Name}</Text>
</View>
))}
</View>
);
}
}
}
You are fetching a huge amount of data and you probably want some sort of pagination with infinite scrolling. It is extremely slow to load due to the huge payload that we are fetching.
You also have double-escape problem in the JSON response inside the geocodingData section. You want to return this data as an object but it is an escaped string with lots of \" instead.

Trying to display JSON Data, but receiving JSON Parse Error

I am trying to display JSON data on my screen, the integer 4 to be exact.
But, I am receiving a JSON Parse Error.
I've posted and that works fine as in Webhooksite says it successfully posted. Also, it "gets" fine, but the data doesn't display. Please help!
// JSON Data
{
"cheetosamount": 4,
"cookiesvalue": 2
}
export default class ChooseDeliveries extends Component {
constructor(props){
super(props);
this.state = {
isLoading: true,
dataSource: null
}
}
componentDidMount(){
this.handleGetRequest();
}
handleGetRequest() {
fetch ('https://webhook.site/e61dd236-92d5-4b3b-882b-a50d6add6cd3',{
method: 'GET',
})
.then(response => response.json())
.then(responseJson => {
this.setState({
dataSource: JSON.parse(responseJson),
isLoading: false,
})
})
.catch(error => {
console.error(error);
});
};
render(){
if(this.state.isLoading){
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
} else {
return(
<View style={{flex: 1, paddingTop:20}}>
<Text>
{this.state.dataSource.cheetosamount}
</Text>
</View>
);
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
I believe its because that 'JSON' that you are getting is already an object and there's no need for you to parse it.
More indepth explaination provided here SyntaxError: Unexpected token o in JSON at position 1
Try the following in your chrome console
let c ={
"cheetosamount": 4,
"cookiesvalue": 2
}
c.cheetosAmount
So essentially all you have to do is
this.setState({
dataSource: responseJson,
isLoading: false,
})

React Native Image Upload as Form Data

Postman formdata is working perfectly, but this returns following http 500 error. what is wrong with this block.
Response {type: "default", status: 500, ok: false, statusText:
undefined, headers: Headers, …}headers: Headers {map: {…}}ok:
falsestatus: 500statusText: undefinedtype: "default"url:
"http://cupdes.com/api/v1/create-user"_bodyInit: ""_bodyText:
""proto: Object "rtghj"
import React, {Component} from 'react';
import {Platform, StyleSheet,View,Image,ScrollView,TextInput,KeyboardAvoidingView,TouchableOpacity,TouchableHighlight,AsyncStorage,} from 'react-native';
import { Container, Header, Content, Button, Text,Input, Label,Item,Form, } from 'native-base';
import Icon from 'react-native-vector-icons/FontAwesome5';
import ImagePicker from 'react-native-image-picker';
export default class SignUp extends Component {
constructor(){
super();
this.state = {
email: "",
name: "",
password: "",
photo: null ,
errors: [],
showProgress: false,
}
}
handleChoosePhoto = () => {
const options = {
noData: true,
};
ImagePicker.launchImageLibrary(options, response => {
if (response.uri) {
this.setState({ photo: response });
}
});
};
onPressSubmitButton() {
console.log("Image ",this.state.photo,this.state.email,this.state.password,this.state.name)
this.onFetchLoginRecords();
}
async onFetchLoginRecords() {
const createFormData = () => {
var data = new FormData();
data.append("image", {
name: this.state.photo.fileName,
type: this.state.photo.type,
uri:
Platform.OS === "android" ? this.state.photo.uri : this.state.photo.uri.replace("file://", "")
});
data.append('name', this.state.name);
data.append('password',this.state.password);
data.append('email', this.state.email);
console.log("aaaa",data);
return data;
};
try {
let response = await fetch(
'http://cupdes.com/api/v1/create-user',
{
method: 'POST',
headers: {
'X-AUTH-TOKEN': 'Px7zgU79PYR9ULEIrEetsb',
'Content-Type': 'multipart/form-data'
},
body:createFormData()
}
)
.then((response) => {
console.log(response,"rtghj")
this.setState({ photo: null });
if (JSON.parse(response._bodyText) === null) {
alert("Internal server error!!!");
}else{
if (JSON.parse(response._bodyText).success === "true") {
this.props.navigation.navigate('loading');
}else{
alert("Data missing!!!");
}
}
})
} catch (errors) {
alert(errors);
}
} SignupHandler=()=>{
this.props.navigation.navigate('DrewerNav')
}
SignuptologinHandler=()=>{
this.props.navigation.navigate('SigntoLogin')
}
render() {
const { photo } = this.state;
return (
<KeyboardAvoidingView
style={styles.wrapper}
>
<View style={styles.scrollWrapper}>
<ScrollView style={styles.scrollView}>
<View style={styles.LogoContainer}>
<Image source={require('../Images/avatar1.png')} style={styles.Logo} onPress={this.handleChoosePhoto} />
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center'}}>
{photo && (
<Image
source={{ uri: photo.uri,
type: "image/jpeg",
name: photo.filename }}
style={{ width: 125, height: 125,borderRadius:80}}
/>
)
}
<TouchableOpacity >
<Icon name="image" size={30} color="#222" marginTop='30' position='absolute' onPress={this.handleChoosePhoto}position='relative'/>
</TouchableOpacity>
</View>
<Text style={styles.createNew1}> CREATE ACCOUNT</Text>
</View>
<View>
<Form style={styles.inputwrapper} >
<Item >
<Icon name="user" size={25} color="white"/>
<Input style={styles.input}
placeholder='Your name'
placeholderTextColor={'white'}
name="name"
onChangeText={text => this.setState({ name: text })}
/>
</Item>
<Item >
<Icon name="mail-bulk" size={25} color="white"/>
<Input style={styles.input}
placeholder='Your e-mail'
placeholderTextColor={'white'}
name="email"
onChangeText={text => this.setState({ email: text })}
/>
</Item>
<Item >
<Icon name="lock" size={25} color="white"/>
<Input style={styles.input}
secureTextEntry
placeholder='Your password'
placeholderTextColor={'white'}
name="password"
onChangeText={text => this.setState({ password: text })}
/>
</Item >
<Item >
<Icon name="unlock" size={25} color="white"/>
<Input style={styles.input}
secureTextEntry
placeholder='Confirm password'
placeholderTextColor={'white'}
name="password"
/>
</Item>
</Form>
</View>
<View>
<TouchableOpacity >
<Button style={styles.btnLogin} onPress={this.onPressSubmitButton.bind(this)}
>
<Text style={styles.text} >Sign Up </Text>
</Button>
</TouchableOpacity>
<TouchableOpacity onPress={this.SignuptologinHandler} >
<Text style={styles.createNew}> Have an account ?LOG IN</Text>
</TouchableOpacity>
</View>
</ScrollView>
</View>
</KeyboardAvoidingView>
);
}
}
I may be very late in posting the answer but it may be helpful for others who encountered the same error. The following workflow worked for me. I used node.js as my backend.
const options = {
quality: 1.0,
maxWidth: 500,
maxHeight: 500,
storageOptions: {
skipBackup: true,
path: 'images',
cameraRoll: true,
waitUntilSaved: true,
},
};
ImagePicker.showImagePicker(options, response => {
if (response.didCancel) {
console.log('User cancelled photo picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else {
let source = response;
this.setState({profileImage: source});
}
});
}
saveToServer(){
let {profileImage} = this.state;
// initilizing form data
let formData = new FormData();
formData.append('file', {
uri: profileImage.uri,
type: 'image/jpeg/jpg',
name: profileImage.fileName,
data: profileImage.data,
});
axios.post('http://192.156.0.22:3000/api/updateProfile', userDetail, {
headers: {'Content-Type': 'multipart/form-data'},
}).then(res => //)
.catch(err => //);
}
And in the node server, I am doing something like this.
//index.js
//..
const formData = require('express-form-data');
//..
//
app.use(formData.parse());
// profile.js
profile.post('/updateProfile', async (req, res) => {
let imageCloud = await cloudinary.v2.uploader.upload(req.files.file.path, {
use_filename: true
});
}
Note: I'm using cloudinary to store my images.
The above code is working for both android and iOS.
I hope this will help you in some extent.
I don't know if you are running into an issue with just Android but I had errors posting images and videos on Android only where I was getting Network Request failed.
More info here Fetch requests failing on Android to AWS S3 endpoint
The solution was basically that the fileType sent in formData needed to be have the '/jpg' or '/mp4' in my cases and ImagePicker only returns type 'image' or 'video'. iOS apparently allows the request fine but Android will not.
its seem to be last replay you can check also this my artical.
uploadImageToServer = () => {
RNFetchBlob.fetch('POST', base.BASE_URL + '/php_imagefileupload.php', {
Authorization: "Bearer access-token",
otherHeader: "foo",
'Content-Type': 'multipart/form-data',
}, [
{ name: 'image', filename: 'image.png', type: 'image/png', data: this.state.data },
{ name: 'image_tag', data: this.state.Image_TAG, data: this.state.username }
]).then((resp) => {
var tempMSG = resp.data;
tempMSG = tempMSG.replace(/^"|"$/g, '');
Alert.alert(tempMSG);
}).catch((err) => {
// ...
})
}
blog url : https://www.banglacleverprogrammer.life/2020/05/react-native-upload-image-to-server.html
I have the same issue, it happens on Android, but works well on IOS.
I found this issue about Flipper_Network.
For now, I commented
initializeFlipper(this, getReactNativeHost().getReactInstanceManager())
in the file MainApplication.java
createFormData = () => {
console.log("RESPOSTA FORMDATA")
console.log("NAME: " + this.state.photo.fileName);
console.log("TYPE: " + this.state.photo.type);
console.log("URI: " + this.state.photo.uri);
console.log("PATH: " + this.state.photo.path);
var foto = {
uri: Platform.OS === "android" ? this.state.photo.uri : this.state.photo.uri.replace("file://", ""),
type: this.state.photo.type,
name: this.state.photo.fileName,
path: this.state.photo.path
};
const fotoUsuario = new FormData();
fotoUsuario.append("foto", foto)
return fotoUsuario;
};