Promise Rejection with axios. try to make HTTP instead of HTTPs [ duplicate ] - react-native

I pull data from the API and write it to the application with usestate() when the app runs there are no problems, but after 10-30 seconds I get this error.
Here is my code.
const App = () => {
const [datas, setDatas] = useState([])
const res = async () => {
const response = await axios.get("http://hasanadiguzel.com.tr/api/kurgetir")
setDatas(response.data.TCMB_AnlikKurBilgileri)
}
res()
return (
<SafeAreaView style={style.container}>
<View>
{datas.map((item) => {
return (
<KurCard
title={item.Isim}
alis={item.BanknoteBuying}
satis={item.BanknoteSelling}
/>
)
})}
</View>
</SafeAreaView>
)
}
How can I fix this ?

Hi #n00b,
The problem is with your URL Protocol.
const App = () => {
const [datas, setDatas] = useState([]);
const res = async () => {
try {
const url = "https://hasanadiguzel.com.tr/api/kurgetir";
const response = await axios.get(url);
const data = await response.data;
console.log(data.TCMB_AnlikKurBilgileri); // check you console.
setDatas(response.data.TCMB_AnlikKurBilgileri);
} catch (error) {
console.log(error);
}
};
useEffect(() => {
res();
}, []);
And also check this out:- Codesandbox.
And please read this Stack Overflow discussion for better understanding:- stackoverflow

Related

React Native with API, Error: undefined is not an object

I'M trying to use Weather API with React Native, but the error below occurred.
It seems that a problem is that const is used before getAdressData done.
How can I use const in this case and fix this error?
Error
undefined is not an object (evaluating 'whether.sys.sunrise')
Codes
〜〜〜〜〜〜〜〜〜〜
export const AddressScreen = () => {
const [address, setAddress] = useState('');
const baseURL = `${APIKey}`
const getAddressData = () => {
axios.get(baseURL)
.then((response) => {setAddress(response.data)})
.catch(error => console.log(error))
};
const sunrise = new Date(weather.sys.sunrise * 1000); //Error
const sunriseTime = sunrise.toLocaleTimeString();
return (
<KeyboardAvoidingView>
〜〜〜〜〜〜〜〜
<View>
<Text>
Sunrise: {(sunriseTime)}
</Text>
</View>
</KeyboardAvoidingView>
);
The JavaScript compiler error is clear with the error. you are trying to access weather.sys.sunrise object property but not defined/initialized.
It seems that you are trying to fetch weather information of a specific location. If that is the intention of your code.
Refactor code as below :
export const AddressScreen = () => {
const [address, setAddress] = useState(null);
const baseURL = `${APIKey}`;
console.log("Fetched weather data:",address)
const getAddressData = () => {
axios
.get(baseURL)
.then((response) => {
console.log("Server response:",response)
setAddress(response.data);
})
.catch((error) => console.log(error));
};
useEffect(() => {
getAddressData();
}, []);
// Don't access weather data until fetched and assigned to state value.
if (!address?.sys) return null;
const sunrise = new Date(address.sys.sunrise * 1000);
const sunriseTime = sunrise.toLocaleTimeString();
return (
<KeyboardAvoidingView>
<View>
<Text>Sunrise: {sunriseTime}</Text>
</View>
</KeyboardAvoidingView>
);
};

Flatlist is very slow in using big data in react native

i have a big data list of products thats paginate, in every page it load 10 item, but when i add new items to itemlist,flatlist gets very slow,As the number of pages increases, so does the loading time of new products,The function of the choose button is also slowed down.
How to speed up loading I tried all the best methods but it still did not work. Did not React Native really solve this problem?
export default function Products(props) {
const toast = useToast();
const [isLoading, setSetIsLoading] = useState(true);
const [items, setItems] = useState([]);
const [fetchStatus, setFetchStatus] = useState(false);
const [page, setPage] = useState(1);
const [sending, setSending] = useState(false);
async function getProducts() {
let token = await AsyncStorage.getItem('#token');
let data = {
token: token,
page: page,
};
await get_products(data)
.then(res => {
setItems([...items, ...res.data.data.docs]);
setPage(res.data.data.nextPage);
})
.catch(err => {
console.log(err);
});
}
async function getNextPage() {
let token = await AsyncStorage.getItem('#token');
let data = {
token: token,
page: page,
};
await get_products(data)
.then(res => {
setItems([...items, ...res.data.data.docs]);
setPage(res.data.data.nextPage);
})
.catch(err => {
console.log(err);
});
}
async function selectProduct(id) {
setSending(true);
console.log({id});
let token = await AsyncStorage.getItem('#token');
let data = {
product_id: id
};
await select_products(data,token).then(res => {
toast.show({
description:res.data.message
})
setSending(false);
}).catch(rej => {
console.log({rej})
toast.show({
description:rej?.response?.data.message,
})
setSending(false);
})
}
useFocusEffect(
React.useCallback(() => {
getProducts();
return () => {
setItems([]);
setPage();
};
}, []),
);
renderItem =({item}) => (
<Card
selectProduct={id => selectProduct(id)}
sending={sending}
obj={item}
/>
)
return (
<View mb={20}>
<FlatList
data={items}
extraData={items}
removeClippedSubviews={true}
renderItem={renderItem}
keyExtractor={(item) => `${item._id}-item`}
onEndReached={getNextPage}
maxToRenderPerBatch="13"
ListFooterComponent={() => {
return <ActivityIndicator color="orange" size="large" />;
}}></FlatList>
</View>
);
}
Did you use **map method **?
It can help you for more easily loading data

Problem with fetching data to React Native application from express server

I'm trying to develop an android application that fetches data from a local server, although I'm not encountering any errors, I'm not getting the requested data. As the title says I'm using React-Native for my frontend application and Nodejs(expressjs) for backend.
( When I make a get request with cURL, it fetches the data successfully. I run the application on browser )
My server code is this :
const express = require('express')
const cors = require('cors')
const app = express()
app.use(cors())
app.get('/' , async (req, res) => {
res.send({"abc" : 123})
});
const PORT = process.env.PORT || 5000
app.listen(PORT, () => console.log(`server started on port ${PORT}`));
My front-end code is this :
import React, { useEffect, useState } from 'react';
import { ActivityIndicator, Text, View } from 'react-native';
const Sandbox = () => {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
const getData = async () => {
try {
const response = await fetch('http://localhost:5000/');
setData(response);
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
}
useEffect(() => {
getData();
}, []);
return (
<View style={{ flex: 1, padding: 24 }}>
{isLoading ? <ActivityIndicator/> : (
<Text>{Object.keys(data)}</Text>
)}
</View>
);
};
export default Sandbox
Try this:
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState();
const fetchData = async (url) => {
const response = await fetch(url);
return response.json();
};
const getData = () => {
try {
fetchData("http://localhost:5000/").then((data) => {
setData(data);
setLoading(false);
});
} catch (error) {
console.error(error);
}
};

TypeError: failed to fetch mern

I'm on Course "React, NodeJS, Express & MongoDB - The MERN Fullstack Guide" Section "Connecting the React.js Frontend to the Backend". Can anyone guide me on why I'm getting this error? Whenever I Update or delete a place it shows the error: TypeError: Failed to fetch What can I do about that?
const UserPlaces = () => {
const [loadedPlaces, setLoadedPlaces] = useState();
const { isLoading, error, sendRequest, clearError } = useHttpClient();
const userId = useParams().userId;
useEffect(() => {
const fetchPlaces = async () => {
try {
const responseData = await sendRequest(
`http://localhost:5000/api/places/user/${userId}`
);
setLoadedPlaces(responseData.places);
} catch (err) { }
};
fetchPlaces();
}, [sendRequest, userId]);
const placeDeletedHandler = deletedPlaceId => {
setLoadedPlaces(prevPlaces =>
prevPlaces.filter(place => place.id !== deletedPlaceId)
);
};
return (
<React.Fragment>
<ErrorModal error={error} onClear={clearError} />
{isLoading && (
<div className="center">
<LoadingSpinner />
</div>
)}
{!isLoading && loadedPlaces && <PlaceList items={loadedPlaces} onDeletePlace={placeDeletedHandler} />}
</React.Fragment>
);
};
export default UserPlaces;
Frontend: https://github.com/sharjeelyunus/peek-mern
Backend: https://github.com/sharjeelyunus/peek-mern-api
Found the answer: that was the cores error. you just have to add cors.
var cors = require('cors');
app.use(cors(), (req, res, next) = {}

react native - why is my console.log returning [] but items get rendered on screen?

I am trying to access the object obtained from my API get request but I keep getting Array[] returned in the console.log while the items get rendered on the screen.
Can someone spot where I went wrong?
const [posts, setPosts] = useState([]);
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);
const loadPosts = async () => {
setLoading(true);
const response = await messagesApi.getMessages();
setLoading(false);
if (refreshing) setRefreshing(false);
if (!response.ok) return setError(true);
setError(false);
setPosts(response.data);
};
useEffect(() => {
const newsocket = io.connect("http://ip:port");
loadPosts();
console.log(posts); // not working
newsocket.on("connect", (msg) => {
setSocket(newsocket);
});
return () => newsocket.close();
}, []);
return (
<FlatList
data={posts}
keyExtractor={(post) => post.id.toString()}
renderItem={({ item, index }) => (
<MessagesList
title={item.title}
onPress={() =>
navigation.navigate(routes.CHAT, { message: item, index, updateView })
}
/>
)}
/>
);
ISSUE
console.log executes before getting an API response.
SOLUTION
console.log would work when you add posts in dependency like
useEffect(() => {
console.log(posts);
}, [posts]); // added posts here