Fetch data from multiple APIs in Remix - reactjs

I started learning Remix and got to a point where I would like to get some data from APIs. I created a loader function, in routes folder (initially I did this in component, which is wrong), where I fetch my API call:
export async function loader() {
const res = await fetch("https://reqres.in/api/users?page=2");
return json(await res.json());
}
After that I used the data in my component, where needed:
const { data } = useLoaderData();
Now I would like to use another API, but I don't know how properly to do that in the loader function
export async function loader() {
const res = await fetch("https://reqres.in/api/users?page=2");
// second API i would like to use but don't know how :(
const faqRes = await fetch("https://jsonplaceholder.typicode.com/posts");
return json(await res.json());
}
How could I use multiple APIs in Remix?

You can return more data:
export async function loader() {
const res = await fetch("https://reqres.in/api/users?page=2");
const faqRes = await fetch("https://jsonplaceholder.typicode.com/posts");
return json({
res: await res.json(),
faqRes: await faqRes.json()
});
}
Then in your component:
const { res, faqRes } = useLoaderData();

What if you want to wait for 1st API data and pass the response to 2nd API?
e.g.
export async function loader() {
const res = await fetch("https://reqres.in/api/users?page=2");
const faqRes = await fetch(`https://jsonplaceholder.typicode.com/posts/${res.userId}`);
return json({
faqRes: await faqRes.json()
});
}

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.

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.

How to connect API in reactjs

I and my team are working in Reactjs and I'm completely new to this my part is Connect to API and I follow many resources on the internet, and I don't know that am I on the right track here the code that I did, can someone tell me what I am doing wrong? This part is on the client I want to connect API to the server.I've recieved error:Unexpected reserved word 'await'
useEffect(()=>{
try {
const requestUrl = 'http://localhost:3000/';
const response = await fetch(requestUrl);
const requestJSON = await response.json();
console.log({responseJSON});
const {data} = responseJSON;
setPostEvent(data)
} catch (error) {
console.log('Failed to fetch post list: ',error.message);
}
fetchPostEvent()
},[events])
useEffect(()=>{
localStorage.setItem('events',JSON.stringify(events));
},[events]) ```
You are to use await key word, in an async function. This is how you would make your function async:
useEffect(async()=>{
try {
const requestUrl = 'http://localhost:3000/';
const response = await fetch(requestUrl);
const requestJSON = await response.json();
console.log({responseJSON});
const {data} = responseJSON;
setPostEvent(data)
} catch (error) {
console.log('Failed to fetch post list: ',error.message);
}
fetchPostEvent()
},[events])

How to pass a value to getServerSideProps?

Using nextjs, I have state that contains the users JWT, This needs to be passed into the request in getServerSideProps.
export async function getServerSideProps(ctx) {
const res = await fetch('http://localhost:1337/publics')
const data = await res.json()
const theData = data[ctx.query.id - 1]
return {
props: {data: theData},
}
}
How can i pass the JWT here?

Axios Error Networ error on request Google place api

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.

Resources