Axios Error Networ error on request Google place api - reactjs

im trying to make a request to google api but returns me network error. If i put the url in the browser, brings me the information correctly.I tryed to formate the request without success. The google places search works correctly too.
export const fetch_information = (skip, limit, filter) => async (dispatch) => {
try {
var url = `https://maps.googleapis.com/maps/api/place/details/json?place_id=ChIJk0aJYPbk3JQRLpKN20Jecko&fields=name,rating,formatted_phone_number&key=MyKey`;
const {data} = await axios.get(url)
console.log(data)
} catch (error) {
console.log(error.message)
}
}
and
export const fetch_information = (skip, limit, filter) => async (dispatch) => {
try {
var url = `https://maps.googleapis.com/maps/api/place/details/json?`;
let config = {
params: {
place_id: 'ChIJk0aJYPbk3JQRLpKN20Jecko',
key: 'myKey',
},
}
const {data} = await axios.get(url, config)
console.log(data)
} catch (error) {
console.log(error.message)
}
}

I think that the request looks a bit messy. I'm under the impression that you are trying to pass results to a redux store. Let's see if we can clean this up a bit.
export const fetch_information = async () => dispatch => {
const req = await axios.get("https://maps.googleapis.com/maps/api/place/details/json?place_id=ChIJk0aJYPbk3JQRLpKN20Jecko&fields=name,rating,formatted_phone_number&key=MyKey");
const data = await req.json();
return data;
//or, for your purpose...
console.log(data);
//can also dispatch for store
}
I didn't see anything you were passing as necessary for this.

Related

axios returns promise instead of data

I am querying some data from IPFS using axios, the problem is that after calling the specific api the return value is a promisse from axios.
const getNFTDetail = async (url: string) => {
const urlIPF = url.replace("ipfs://", "https://cloudflare-ipfs.com/ipfs/");
try {
return await axios.get(urlIPF).then((res) => {
return res.data;
});
} catch (error) {
console.log(error);
}
};
response I get:
is there a way to wait until promisse has been resolved?, as you see I am already using async await on the function call.
just, decide if you use async / await or .then / .catch:
const getNFTDetail = async (url: any) => {
const urlIPF = url.replace("ipfs://", "https://cloudflare-ipfs.com/ipfs/");
const { data } = await axios.get(urlIPF);
return data;
};
or
const getNFTDetail = (url: any) => {
const urlIPF = url.replace("ipfs://", "https://cloudflare-ipfs.com/ipfs/");
axios.get(urlIPF).then(({data}) => {
// use your data here
}).catch((err)=>{
console.log(err);
};
};
When you fetch a request, no matter any http client you use, will then return a Promise.
Just use await to get a response from your request.
const response = await axios.get(your-url);
const json = await response.json();
To use typescript correctly, type the url a string: (url: string) instead of happy any type.

GitHub API getRepos async request turn back a promise instead of an array of repos

I have a problem with async request return. It returns me back a Promise instead of data!!
So i tried to process data variable a second time but it did not work. I exported it as it needs, created initial state for repo=[], passed in to the reducer...
gitContext.jsx
const getRepos = async (login) => {
setLoading();
const params = new URLSearchParams({
sort:'created',
per_page:10
})
const response = await fetch(`http://api.github.com/users/${login}/repos?${params}`)
if (response.status === 404) {
window.location = './notfound'
} else {
const data = await response.json();
console.log(data);
dispatch({
type: 'GET_REPOS',
payload: data
})
}
}
Here is the function call from User.jsx
const { getUser, user, isLoading, repos, getRepos } = useContext(GitContext);
const params = useParams()
useEffect(() => {
getUser(params.login);
// console.log(getRepos(params.login?.repos))
getRepos(login?.repos);
}, [])

React Query "Fetching" state but not sending request to server

I'm having a recurrent problem with react query. On some queries, the query says "fetching" (blue color), but the request to the server "doesn't go through". It's "suspended" or something. And I tried console.logging on my nodeJS controller (associated with the GET endpoint), but the function isn't even called.
This is quite annoying (and to be clear, this is with new queries which aren't stale or cached).
This is my query:
const postDetails = useQuery(
["post", postId],
async () =>
await fetch(
"http://localhost:5000/api/post/id/" + postId
).then((res) => res.json()),
{
onSuccess: (data) => {
console.log(data);
},
}
);
This is what React Query Devtools says:
This is what the network tab says:
Thanks in advance.
I believe your use of await and .then is giving you issues. I would recommend just sticking with await
const postDetails = useQuery(
["post", postId],
async () =>
try {
let res = await fetch(
"http://localhost:5000/api/post/id/" + postId
)
res = await res.json()
} catch(err) {
console.error(err)
}
{
onSuccess: (data) => {
console.log(data);
},
}
);
This method uses a trycatch for error handling, and does not rely on .then which I believe is where the issue lies.
Try separating the fetch function from the query:
async function fetchPosts() {
try {
const res = await fetch(
"http://localhost:5000/api/post/id/" + postId
)
const json = await res.json()
return json
} catch (err) {
console.error(err)
}
}
const postDetails = useQuery(
["post", postId],
fetchPosts,
{
onSuccess: (data) => {
console.log(data);
},
}
);

React Query useQuery & Axios

I'm trying to create an API function with a help of React Query and Axios.
When I'm using useQuery with vanilla fetch function - it all works perfectly.
export const useGetDebts = async () => {
const { families } = appStore.user;
const res = useQuery("getDebts", async () => {
const res = await fetch(`${API_URL}/api/family/${families[0]}/debts`, {
method: "GET",
headers: {
Authorization: `Bearer ${appStore.token ?? ""}`,
},
});
const parsedBody: DebtsResponse = await res.json();
return parsedBody;
});
return res;
};
But when I switch the vanilla fetch function to Axios - I get an error status of 500 (not sure if it comes from React Query or Axios).
export const useGetDebts = async () => {
const { families } = appStore.user;
const res = useQuery("getDebts", async () => {
const res = await axiosInstance.get<DebtsResponse>(`/api/family/${families[0]}/debts`);
return res.data;
});
return res;
};
Thanks in advance for any explanations/suggestions.
P.s. The axiosInstance works fine with the useMutation hook. So it only makes me more confused. =(
export const useGetDebt = () => (
useMutation(async (id: number) => {
const { families } = appStore.user;
const res = await axiosInstance.get<DebtResponse>(`/api/family/${families[0]}/debts/${id}`);
return res.data;
})
);
P.s.s. I'm working with React Native if it's somehow relevant.
react-query doesn't give you any 500 errors because react-query doesn't do any data fetching. It just takes the promise returned from the queryFn and manages the async state for you.
I'm not sure if the fetch code really works because it doesn't handle any errors. fetch does not transform erroneous status codes like 4xx or 5xx to a failed promise like axios does. You need to check response.ok for that:
useQuery(['todos', todoId], async () => {
const response = await fetch('/todos/' + todoId)
if (!response.ok) {
throw new Error('Network response was not ok')
}
return response.json()
})
see Usage with fetch and other clients that do not throw by default.
So my best guess is that the fetch example also gives you a 500 error code, but you are not forwarding that error to react-query.

Fetch console login twice

I'm trying to fetch from the PokemonAPI but when I console.log my response, it logs twice, and I don't know if that's a problem or not. I'm doing it with Reactjs. My code:
const fetchPokemon = async () => {
try {
const res = await fetch('https://pokeapi.co/api/v2/pokemon/1')
const pokemon = await res.json()
console.log(pokemon)
} catch (err) {
console.log(err)
}
}
fetchPokemon()
In React functional components API call should be placed inside useEffect() function, this will resolve your issue.
useEffect(() => {
async function apiCall() {
const res = await fetch('https://pokeapi.co/api/v2/pokemon/1')
const pokemon = await res.json()
console.log(pokemon)
}
apiCall();
}, []);

Resources