How to connect API in reactjs - 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])

Related

Fetch data from multiple APIs in Remix

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()
});
}

next-auth get request issue returns null

i'm having a problem when i request GET to my api it returns me unauthenticated even though im logged in
my api code basically getSession returns null when im fetching on getServerSideProps but when im fetching on client side (useEffect it works perfectly)
i wanted a ssr that's why im trying to fetch in getServerside props
const handler = async (req, res) => {
if (req.method === "GET") {
const session = await getSession({ req });
if (!session) {
res.status(401).json({ message: "Not Authenticated" });
return;
}
const userId = session.user.id;
const client = await connectDb();
const db = client.db();
const tasks = await db
.collection("tasks")
.find({ user_id: userId })
.toArray();
res.status(200).json(tasks);
}
};
when i try to fetch on serverside it returns me message: "Not Authenticated"
export const getServerSideProps = async (context) => {
const res = await fetch(`http://localhost:3000/api/tasks`);
const data = await res.json();
return {
props: { data },
};
};
but when i fetch using useEffect (Client side) it works
useEffect(() => {
const fetchData = async () => {
const res = await fetch(`http://localhost:3000/api/tasks`);
const data = await res.json();
console.log(data);
};
fetchData();
}, []);
sorry i'm still new with this thank you in advance

Fetching problem with react, I am trying to fetch movie name from local api than based on that movie name fetch movie data from another api

So I'm fetching movie name from localhost with getMovie function, and based on that name I fetch from online API. When i console.log name(that i got from getMovie function) constant i get undefined, then i get real movie name. Below are my function for fetching. Hope someone can help I am really stuck with this. :)
async function getMovie() {
try {
const response = await fetch(`http://localhost:5000/dashboard/movies/movie/${movieId}`, {
method:"GET",
headers: { "Content-Type": "application/json" }
})
const parseRes = await response.json()
setMovieFromBase(parseRes[0])
} catch (error) {
console.error(error.message)
}
}
const {movie_name} = movieFromBase
console.log(movie_name)
const fetchPopular = async() => {
try {
const data = await fetch(`https://api.themoviedb.org/3/search/movie?API_KEY&query=${name}`)
const movies = await data.json()
console.log(movie)
setMovie([movies.results[0]])
console.log(movie)
} catch (error) {
console.error(error.message)
}
}

Why do I keep getting Syntax Error: JSON parse even though my code works with another API?

Working with React and I continually get a SyntaxError:JSON.parse when I try to fetch from the API. I'm able to fetch the data just fine when working with a different API.
What am I doing wrong here? I'm a complete newb when it comes to API's so please don't eviscerate me if this is a stupid question :D
const API_URL = 'www.themealdb.com/api/json/v1/1/search.php?s=Arrabiata';
const getMealRequest = async()=>{
const response = await fetch(API_URL)
const data = await response.json()
console.log(data)
}
useEffect(()=>{
getMealRequest()
},[])
There is an error on your API call which is not related to this question. You didn't implement try/cath block with the getMealRequest so in the failure case, the response is not a valid object to parse and you get the mentioned error.
To solve it:
const getMealRequest = async () => {
try {
const response = await fetch('https://www.themealdb.com/api/json/v1/1/search.php?s=Arrabiata'
)
const data = await response.json()
console.log(data)
} catch (error) {
console.log(error)
}
}
Now inspect your console and see what is wrong with your API call. also, you can check the network tab for further detail about the request and response on calling API_URL.
const API_URL = 'https://www.themealdb.com/api/json/v1/1/search.php?s=Arrabiata';
const getMealRequest = async() => {
const response = await fetch(API_URL)
const data = await response.json()
console.log(data)
}
getMealRequest()
You forgot to include protocol:
incude https:// before the address and it will work:

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