Api data not being displayed due to CORS -axios. ReactJS - javascript

I am making an api call to the steam review api with this link: "api link"
I have used another link with my code and was able to get responses and even display the data on my screen, so I have no faulty code. I am currently using this to try and get the result content: comment.reviews.review
This is my complete code:
function Home() {
const [comments, setComments] = useState([]);
useEffect(() => {
fetchComments();
}, []);
useEffect(() => {
console.log(comments);
}, [comments]);
const fetchComments = async () => {
const response = await axios(
"https://store.steampowered.com/appreviews/1389990?json=1&language=english"
);
setComments(response.data);
};
var limitComments = comments.slice(0, 3);
return (
{limitComments &&
limitComments.map((comment) => (
<p>{comment.reviews.review}</p>
))}
);
}
export default Home;
What is wrong with request? I have tried using different keys like comment.author.reviews.review.

You'll want to brush up on CORS since that's what's preventing your request from succeeding. Here's a great resource:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Related

Firebase fetching + React: Images won't load and getting a 500 error, but if I keep refreshing they show up

So I'm currently brushing up my react skills and learning firebase. I found it simple enough to configure and now I have been successfully making fetch requests from my realtime database.
I am currently building some sort of a birthday app that would show monthly and daily celebrants, and have generated mock data that I imported into my database. Currently, the first names are being fetched successfully and displaying on the screen, however the images (that are hosted on another site and fetched as a string from the db) are not loading properly and I'm getting 500 error in my console. If I keep refreshing though, they eventually load.
I'm thinking it must be with the way I make my fetch request. I basically fetch all users and then make a filter (have not explored fetching with queries yet) so I thought it would work.
This is the code for the fetch requests.
export const getUsers = () => {
const usersDb = ref(database);
return get(child(usersDb, `/users`)).then((snapshot) => {
return snapshot.val();
});
};
export const getMonthlyCelebrants = async () => {
const users = await getUsers();
const monthlyCelebs = [];
for (let user in users) {
const userMonth = +users[user]["birth_date"].split("/")[1];
userMonth === getMonthNum() && monthlyCelebs.push(users[user]);
}
return monthlyCelebs;
};
And this is the Monthly Celebrants component I use them in:
export default function Monthly() {
const [monthlyCelebs, setMonthlyCelebs] = useState([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
async function loadPage() {
setIsLoading(true);
const users = await getMonthlyCelebrants();
setIsLoading(false);
setMonthlyCelebs(users);
}
loadPage();
}, []);
return (
<div>
<h2>{getMonthAndYear()} Celebrants</h2>
{isLoading ? (
<p>Celebrants loading...</p>
) : (
sortBirthdays(monthlyCelebs).map((monthlyCeleb) => {
return (
<SingleMonthlyCelebrant
monthlyCeleb={monthlyCeleb}
key={`${monthlyCeleb.birth_date}${monthlyCeleb.first_name}`}
/>
);
})
)}
</div>
);
}
Any tips or advice would be greatly appreciated. Thank you!

How to pass user query to Next.js api?

I'm using the Listen Notes podcast-api in Next.js api routes. I want the user query from my front-end form to interact with the Next.js api. So when a user inputs "history", it will send that to the api to look for podcasts that are about that topic.
I tried adding params to axios request but that doesn't seem to work.
Front-end:
export default function SearchBar() {
const [query, setQuery] = useState("");
const [address, setAddress] = useState("");
const fetcher = async (url) => await axios.get(url, { params: {q: query } }).then((res) => res.data);
const { data, error } = useSWR(address, fetcher);
const handleSubmit = (e) => {
setAddress(`/api/podcast`);
e.preventDefault();
};
return (
<>
<Form onSubmit={handleSubmit}>
<Input
onChange={(e) => setQuery(e.target.value)}
/>
<SearchButton type="submit">Search</SearchButton>
</Form>
</>
);
}
Api code:
const { Client } = require("podcast-api");
export default function handler(req, res) {
const client = Client({
apiKey: process.env.REACT_APP_API_KEY || null,
});
//"q" below should contain the user query from front-end
client
.search({ q: req.params })
.then((response) => {
res.status(200).json(response.data);
})
.catch((error) => {
console.log("apiError: " + error);
});
}
Please let me know if I need to provide more information.
Check if API on you NextJs app, is receiving correctly the environment variable process.env.REACT_APP_API_KEY. Use console.log to test.
Reference :
https://nextjs.org/docs/basic-features/environment-variables
Another check is the API path, cause NextJs use your own method to path this, you know ?!
Reference :
https://nextjs.org/docs/api-routes/introduction
Hope this tips help you ;)
The problem was in the api route, it should be:
.search({ q: req.query.q })
req.params is something else on server side and that's why it wasn't coming through.

Axios is not getting response on first load

I am new in React JS and trying to get the data inside useEffect and I have a separate function for my api, but when I check the data.next in console.log there is no data in the first load but after adding few changes it works fine but still has an error when I refresh the page. Also, I noticed when I tried to console.log inside of function where the Axios or api declared, there's already a data in the first load of an application. Did anyone encounter this issue? Or my approach is wrong?
Here are my codes
/src/App.js
useEffect(async () => {
const res = await service.apiPokemon.fetchAll();
console.log(res.data.next)
}, []);
/src/api/pokemon.js
import axios from 'axios';
const URL = 'https://pokeapi.co/api/v2/pokemon';
export const fetchAll = async () => {
try {
const res = await axios.get(URL);
console.log(res.data.next);
return res;
} catch (error) {
console.log(error);
};
};
This is a very common problem. Your content is loaded before fetching the data. To solve this, you can add a condition to not render your content until you get the data:
let [pokemonsList, setPokemonsList] = useState([])
// Your useEffect hook to fetch data on mount
return (
{ pokemonsList.lenght > 0 && // If you are sure you'll receive pokemons
<div> {pokemonList.map((pokemon) => (
<p> {pokemon.name} </p>
)} </div>
}
)
Now, you'll only see the names of the pokemons when you have the list.
You can also add a loading message in case the response takes time with Redux and selectors.

getStaticProps Does not return any data to the pages on Next.JS

I'm trying to fetch a data from my hosted database. The database itself are working (I have checked it from the swagger app) but no data is shown when it is called from API form.
import React from 'react';
export const getStaticPaths = async () => {
const res = await fetch('https://[server]/course');
const data = await res.json();
const paths = data.result.map(course => {
return {
params: { id: course._id.toString() }
}
})
return {
paths,
fallback: false
}
}
export const getStaticProps = async (context) => {
const id = context.params.id;
const res = await fetch('https://[server]/course/' + id);
const data = await res.json();
return {
props: { course: data }
}
}
const Details = ({ course }) => {
return (
<div>
<h1> { course.course_name } </h1>
<h1>a</h1>
</div>
);
}
export default Details;
The code is in the pages folder. I followed a tutorial on youtube from "netninja" and when I tried it on his code it works. I read somewhere that it won't work on components but I already put it on the pages but it still does not return anything.
Is there anything I can do ?
I got the answer. After checking console.log on the data. Looks like the data is on another array which is called result. so i needed to call the data from course.result.course_name. So the Answer is just to check console.log every once in a while. Shout out to juliomalves for pointing that out

fetch the api data and put it inside the tables

I am trying to fetch the api data and put it inside the tables, now i am using mock data
so I was able to write successfully actions and reducers.
now I am able to call the api.
but in the network call I am not see response in the api and seeing blocked response content status.
I am using react hooks for react and redux.
this is where I am making the api call
useEffect(() => {
getPosts(channel);
}, []);
can you tell me how to fix it.
providing my code snippet and sandbox below.
https://codesandbox.io/s/material-demo-kpt5i
demo.js
const channel = useSelector(state => state.channel);
const dispatch = useDispatch();
const getPosts = channel => dispatch(fetchPosts(channel));
useEffect(() => {
getPosts(channel);
}, []);
actions.js
export function fetchPosts(channel) {
return function(dispatch) {
dispatch(requestPosts());
return fetch(`http://jsonplaceholder.typicode.com/users`)
.then(
response => response.json(),
error => console.log("An error occurred.", error)
)
.then(json => {
dispatch(receivedPosts(json));
});
};
}
according to your sample on codesandbox, it is due to you are loading from https site but your source is from http. change http://jsonplaceholder.typicode.com/users to https://jsonplaceholder.typicode.com/users will solve your issue.

Categories

Resources