React Native: Why isn't this invocation of fetch working? - reactjs

I have the following invocation of fetch in my React Native app:
test = async () => {
try {
let a = await fetch('https://rxapitest.alliancepharmacygroup.ca:12345/', {
method,
}).then(response => {
console.log("success")
})
} catch(err) {
console.log("error")
}
}
Normally I'm hitting actual endpoints from this API with a bearer token, but none of them is working, so I tried the more basic task of just hitting the web page itself. When I run this from Postman it works fine. I'm using React Native v0.62.1.
Does anyone know how I can approach this?

Related

Axios API call returns a 404 on page render, but still returns api objects in terminal

I am using axios to make an api call to an api found on Apihub for a next JS app.
here is the code for the function to make the call to provide a list of property JSON objects.
export const baseUrl = "https://zillow56.p.rapidapi.com"
export const fetchApiListsingsCustom = async (url) => {
const { data } = await axios.get((url), {
method: 'GET',
headers: {
'X-RapidAPI-Key': '328713ab01msh862a3ad609011efp17e6b4jsn0e7112d5ee9a',
'X-RapidAPI-Host': 'zillow56.p.rapidapi.com'
}
});
data.then((res) => {
console.log(res);
})
.catch((error) => {
console.error(error);
});
return data.json();
}
When rendering the page I'm attempting to inject the response's data to dynamically create a list of apartment listings.
I'm trying to use getServerSideProps so that the data is already available by the time a user requests the page. After fetching the data, I want to also print them in the terminal to validate it's success.
export default function Home({ propertiesCustomdata })
export async function getServerSideProps() {
const propertiesCustom = await fetchApiListsingsCustom(`${baseUrl}`)
const propertiesCustomdata = propertiesCustom.json()
return {
props: {
propertiesCustomdata
}
}
}
The problem is, I seem to be getting a 404 error from the axios call, before the page gets a chance to load. When I access this I get a 404 error but I also manage to receive some contents of the call the API was to make.
My apologies if this is unclear, but this is all I know to report on this so far.
Studying async and await, fetch, and axios. Very confusing.

OpenApi generated typescript not properly calling api from React Webapp

I have a react webapp and a spring boot java backend api. The backend Api works perfectly fine with postman.
In the react webapp, I am using openapi generated typescript to make the calls to the backend api. I have two parameters for the api, a number and an object. The object is just json style object.
When I use the typescript to call the api, for some reason, it passes in null for the object parameter and the api returns a 500 error. I have no clue why this is happening. Any suggestions? Here is the code where I call the api:
function gatherUserData(){
const UserDataRetval: UserData = {};
UserDataRetval.version = kVersion;
UserDataRetval.Methods = [];
if (checkedLikesYouCount){
UserDataRetval.Methods.push(UserDataMethodsEnum.RECOM_LIKES_YOU_COUNT)
}
if (checkedRecosRecommendations){
UserDataRetval.Methods.push(UserDataMethodsEnum.RECOS_RECOMMENDATIONS)
}
if (checkedUsersRecommendations){
UserDataRetval.Methods.push(UserDataMethodsEnum.USERS_RECOMMENDATIONS)
}
if (checkedProfileUser){
UserDataRetval.Methods.push(UserDataMethodsEnum.PROFILE_USERID)
}
if (checkedProfile){
UserDataRetval.Methods.push(UserDataMethodsEnum.PROFILE)
}
if (checkedRecosLikesYou){
UserDataRetval.Methods.push(UserDataMethodsEnum.RECOS_LIKES_YOU)
}
if (checkedRecommendationsLikesYou){
UserDataRetval.Methods.push(UserDataMethodsEnum.RECOM_LIKES_YOU)
}
return UserDataRetval;
}
//USER CLICKS SUBMIT BUTTON, CHECKS USERID ISNT EMPTY, BRINGS UP JSON DATA
function handleSubmit() {
console.log("Call API for methods:")
console.log(userid)
SetDisplayJson(userid !== "")
auth.onAuthStateChanged(user => {
if (user) {
user.getIdTokenResult(false)
.then(tokenResult => {
console.log("token: ", tokenResult.token)
new ServiceApi(headerConfig(tokenResult.token)).simulateUser(parseInt(userid), gatherUserData()).then((response) => {
console.log(response);
}, (error) => {
console.log(error);
})
}).catch(e => console.log(e))
}
})
}

How can I deal with CORS issue with create-react-app?

I'm trying to get data from images.google.com with axios.get on my create-react-app application and hosting by firebase.
This is the function of getting request results data from the URL.
const getImage = (transcript) => {
console.log("getImage executed,", transcript[transcript.length-1])
axios.get(`/images?&um=1&hl=en&nfpr=1&q=${transcript[transcript.length-1]}`)
.then((res)=> {
const search = document.querySelector(".search");
search.innerHTML = res.data;
search.querySelectorAll("img").forEach((element) => {
if(element.hasAttribute("data-src")){
const firstImage = element.getAttribute('data-src');
images.push(firstImage);
setSearchResult(images[images.length-1]);
}
});
console.log(res);
})
.catch((error) => {
console.log(error);
})
}
and on package.json I added
"proxy": "https://images.google.com"
but of course still blocked by CORS.
error
I know this is wrong and I think I don't understand the concept of middleware or backend server stuff enough.
So is there any idea to solve this problem in an easy way? Thanks.

I cannot implement DJANGO REST API with REACT

I want to integrate React with Django REST API for my ecom website but for some reason that does not work. I really do not know what I missed. Any input is welcomed.
Please see the code below.
REACT
Home.js (this is the code for products)
const loadAllProducts = () => {
getProducts()
.then((data) => {
if(data.error) {
setError(data.error); //box filled with data error
console.log(error); // message "error"
} else {
setProducts(data); // box filled with data product
}
});
loadAllProducts();
};
coreapicalls.js (here I want to fetch the data)
import { API } from "../../backend.js";
export const getProducts = () => {
return fetch(`${API}product`, { method: "GET" })
.then(response => response.json())
.catch((err) => console.log(err));
};
.env (I have both of my servers running, the url and symbol "/" are correct.)
REACT_APP_BACKEND = http://localhost:8000/api/
My compiler returns no specific error.
./src/core/Home.js
Line 16:11: 'loadAllProducts' is assigned a value but never used no-unused-vars
./src/core/Card.js
Line 26:11: 'getAredirect' is assigned a value but never used no-unused-vars
DJANGO (settings.py, Django does give me JSON data on the localhost:8000/api/product/)
'api',
'api.category',
'api.product',
Best,
Rok.
I went into chrome devtools and saw a "cors error" under network. I forgot to run "pip install django-cors-headers" . The configuration on the DJANGO REST API for corsheaders was correct.

How do I make an HTTP request in react-redux?

I am just getting started with react and I'm a bit lost. I'm trying to make a login page and make a http post request. Right now I'm just trying to get any type of HTTP request working, so I'm using request bin and I found this basic action in the docs for an npm package (https://www.npmjs.com/package/redux-react-fetch):
export function updateTicket(ticketId, type, value){
return {
type: 'updateArticle',
url: `http://requestb.in/1l9aqbo1`,
body: {
article_id: ticketId,
title: 'New Title'
},
then: 'updateTicketFinished'
}
}
So, after writing an action, what do I do? How do I actually get my app to call on and use that action? The docs for the npm package mention something about setting a state in my store, is that something I need to set up first?
You can try any of the following. I have used both fetch and axios they work amazingly well. Yet to try superagent.
For making requests you can either use fetch with
fetch-polyfill for compatibility across all browsers (link)
Axios library. (link)
Superagent with promises.(link)
If you use fetch you would need to use polyfill since it is not supported in IE and safari yet. But with polyfill it works pretty well. You can check out the links for how you can use them.
So what you would doing is in your action creator you can call an API using any of the above.
FETCH
function fetchData(){
const url = '//you url'
fetch(url)
.then((response) => {//next actions})
.catch((error) => {//throw error})
}
AXIOS
axios.get('//url')
.then(function (response) {
//dispatch action
})
.catch(function (error) {
// throw error
});
So that was for the API call, now coming to the state. In redux there is one state which handles your app. I would suggest you should go through redux basics which you can find here . So once your api call succeeds you need to update your state with the data.
Action to fetch data
function fetchData(){
return(dispatch,getState) =>{ //using redux-thunk here... do check it out
const url = '//you url'
fetch(url)
.then (response ) => {dispatch(receiveData(response.data)} //data being your api response object/array
.catch( error) => {//throw error}
}
}
Action to update state
function receiveData(data) {
return{
type: 'RECEIVE_DATA',
data
}
}
Reducer
function app(state = {},action) {
switch(action.types){
case 'RECEIVE_DATA':
Object.assign({},...state,{
action.data
}
})
default:
return state
}
}

Resources