react.js : fetched data is undefined outside of api folder - javascript

I am trying to make a web application using Motorcycle Specs Database API from rapidAPI.
I want to export fetched data from index.js to App.js so that I can use the data in the app. But, when I try to console.log the fetched data in componentDidMount function in App.js, it is undefined. I don't know why at the moment, can you see why??
/api/index.js
import axios from "axios";
const options = {
method: 'GET',
url: 'https://motorcycle-specs-database.p.rapidapi.com/model/make-name/Yamaha',
headers: {
'X-RapidAPI-Host': 'motorcycle-specs-database.p.rapidapi.com',
'X-RapidAPI-Key': 'MYAPIKEY'
}
};
export const fetchData = async ()=>{
await axios.request(options).then(function (response) {
console.log(response.data);
return response.data;
}).catch(function (error) {
console.error(error);
});
}
App.js
import logo from './logo.svg';
import './App.css';
import {fetchData} from './api/index';
import React, {Component} from 'react';
class App extends React.Component{
state = {
data:[],
}
async componentDidMount(){
const fetchedData = await fetchData();
console.log('fetchedData is like this',fetchedData);
this.setState({data:fetchedData});
}
render(){
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}
export default App;

Use try/catch instead of chaining then and catch to your promise:
export const fetchData = async () => {
try{
const { data } = await axios.request(...);
return data;
} catch (errors) {
console.log(errors);
}
}

Related

react.js: 429 (Too Many Requests) when making 2 requests using axios

I am trying to learn React by making a motor cycle spec search web application.
I am making two axios requests in /api/index.js, and I am getting an error saying
'429 (Too Many Requests)'.
What am I doing wrong here?
/api/index.js
import axios from "axios";
const options1 = {
method: 'GET',
url: 'https://motorcycle-specs-database.p.rapidapi.com/model/make-name/Yamaha',
headers: {
'X-RapidAPI-Host': 'motorcycle-specs-database.p.rapidapi.com',
'X-RapidAPI-Key': 'MyAPIKey'
}
};
const options2 = {
method: 'GET',
url: 'https://motorcycle-specs-database.p.rapidapi.com/make',
headers: {
'X-RapidAPI-Host': 'motorcycle-specs-database.p.rapidapi.com',
'X-RapidAPI-Key': 'MyAPIKey'
}
};
export const makeList = async()=>{
try{
const {data} = await axios.request(options2);
console.log('list of all makes is like this now', data);
return data;
}
catch(error){
}
}
export const fetchData = async ()=>{
try{
const {data} = await axios.request(options1);
return data;
}
catch(error){
}
}
and this is where I'm trying to use the data.
App.js
import logo from './logo.svg';
import './App.css';
import {fetchData, makeList} from './api/index';
import React, {Component} from 'react';
class App extends React.Component{
state = {
data:[],
makes:[],
}
async componentDidMount(){
const fetchedData = await fetchData();
const fetchedMakeList = await makeList();
this.setState({data:fetchedData, makes:fetchedMakeList});
//this.setState({makes:fetchedMakeList});
console.log('list of all makes in componentDIDMOUNT is like ', fetchedMakeList);
//why is this undefined??
}
render(){
return (
<div className="App">
<header className="App-header">
<h1>Some line-ups from YAMAHA</h1>
{partOfTheArray.map(data=>{
return <p>{data.name}</p>
})}
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Open React
</a>
</header>
</div>
);
}
}
export default App;
I am only requesting 2 requests, but I am getting this error message.
Assuming that you're trying to fetch data when component mounts, here is a better approach to do so:
// Import useState and useEffect
import React, {useState, useEffect} from 'react';
export default function SomeComponent() {
let [data, setData] = useState(null)
// use an useEffect with empty dependecy(empty [] as a dependecy) to fetch the data
// empty [] makes sure that you're fetching data only once when the component mounts
useEffect(() => {
fetchData().then(res => {
// check status for response and set data accordingly
setData(res.data)
// log the data
console.log(res.data)
})
},[])
return (
<div className="App">
</div>
);
}
You need to update your fetchData() function as well.
export const fetchData = async ()=>{
try{
const response = await axios.request(options1);
// return the whole response object instead of only the data.
// this helps in error handling in the component
return response;
}
catch(error){}
}
I hope it helps!

Having trouble displaying api data on the page?

Im making a project where I fetch an image of a recipe card from https://spoonacular.com and I want it displayed on my react.js app. For some reason I can't get the API data from displaying on the page when I run it. Please help Im really stuck. I keep getting the error that recipeList is undefined in Recipe.js but I thought it was defined?
This is my Home.js:
import React, { useEffect, useState } from "react";
import axios from "axios";
import Recipe from "../components/Recipes";
const URL = `https://api.spoonacular.com/recipes/716429/information?apiKey=${APIKey}&includeNutrition=false`;
function Home() {
const [food, setFood] = useState();
useEffect(() => {
if (food) {
axios
.get(URL)
.then(function (response) {
const recipeList = response.data;
setFood(recipeList);
})
.catch(function (error) {
console.warn(error);
});
}
}, [food]);
return (
<main>
<Recipe recipeList={food} />
</main>
);
}
export default Home;
this is my Recipe.js
import React from "react";
function Recipe({ recipeList }) {
return (
<div className="Recipe">
<div>{recipeList.title}</div>
<img src={recipeList.image} />
</div>
);
}
export default Recipe;
you need initializing empty
const [food, setFood] = useState({});
and in useEffect evaluate if food is empty
useEffect(() => {
const getData=()=>{
axios
.get(URL)
.then(function (response) {
const {data} = response;
setFood(data);
})
.catch(function (error) {
console.warn(error);
});
}
if(!food){ // validate if food is empthy to get data (food)
getData()
}
}, []); // here is not necesary use food, because never happen anything with that variable
The response example can be seen here.
To call that using axios:
import React, { useEffect, useState } from "react";
import axios from "axios";
import Recipe from "../components/Recipes";
const URL = `https://api.spoonacular.com/recipes/716429/information?apiKey=${APIKey}&includeNutrition=false`;
function Home() {
const [food, setFood] = useState({});
useEffect(() => {
// You can add any if-else statement here
// but you can also do the fetch without it
axios
.get(URL)
.then(function (response) {
setFood(response.data);
})
.catch(function (error) {
console.warn(error);
});
}, []);
return (
<main>
<Recipe recipeList={food} />
</main>
);
}
export default Home;
And based on the response, your Recipe.js should working properly.

How do I display data from an external API on react js?

Im building an app where I want to take api data from https://www.thecocktaildb.com to allow for users to search for a cocktail drink and it will fetch data from the api source to display the name of the drink on the page. I don't know why its giving me an error of "Uncaught TypeError: drinkList.drinks is undefined" because if you look at the screenshot I included of what the JSON data looks like, it should be correct?
This is my Home.js
import React, { useEffect, useState } from "react";
import axios from "axios";
import Drinks from "../components/Drinks";
function Home() {
const [drinkName, setDrinkName] = useState();
const drinksURL = `https://www.thecocktaildb.com/api/json/v1/1/search.php?s=${drinkName}`;
function handleChangeDrink(e) {
setDrinkName(e.target.value);
}
const getDrink = () => {
axios
.get(drinksURL)
.then(function (response) {
setDrinkName(response.data);
console.log(drinksURL);
})
.catch(function (error) {
console.warn(error);
});
};
return (
<main className="App">
<section className="drinks-section">
<input
type="text"
placeholder="Name of drink (e.g. margarita)"
onChange={handleChangeDrink}
/>
<button onClick={getDrink}>Get a Drink Recipe</button>
<Drinks drinkList={drinkName} />
</section>
</main>
);
}
export default Home;
and this is my Drinks.js component
import React from "react";
function Drinks({ drinkList }) {
if (!drinkList) return <></>;
return (
<section className="drinkCard">
<h1>{drinkList.drinks[0].strDrink}</h1>
</section>
);
}
export default Drinks;
This is a screenshot of the JSON data:
You should define the new variable for drink list
const [drinkList, setDrinkList] = useState([]);
And you should assign your response to this variable here (instead of assigning drinkName):
const getDrink = () => {
axios
.get(drinksURL)
.then(function (response) {
setDrinkList(response.data);
console.log(drinksURL);
})
.catch(function (error) {
console.warn(error);
});
};

i am trying to change the state of my component with this.SetState(), but its no working

import React, { Component } from 'react';
import Navbar from './components/Navbar';
import Landingpage from './components/Landingpage';
import Mainbody from './components/Mainbody';
import './App.css';
import axios from 'axios';
import { FORTNITE_IO } from './config'
class App extends Component {
state = {
itemShop: {},
test: 'damiisdandy'
};
getItemShop = () =>
axios.get('https://fortniteapi.io/shop?lang=en', {
headers: {
Authorization: FORTNITE_IO
}
})
.then(res => res.data)
.catch(err => err);
componentDidMount() {
this.setState({itemShop: this.getItemShop()})
this.setState({test: 'feyi'})
console.log(this.state)
}
render() {
return (
<div className="App">
<div className="sil">
<img style={{ zIndex: 0 }} src="./img/glider-sil.png" alt=""/>
</div>
<Navbar />
<Landingpage />
<Mainbody />
<footer>
<img src="./img/midas3.png" alt="geng"/>
<img className="footer-img" src="./img/midas1.png" alt="geng"/>
</footer>
</div>
)
}
}
export default App;
I am new to react,
i am making a request with axios and trying to update my state with the response data
I am trying to update the state with this.Setstate() but it doesn't seem to update the state at all.. please i need help!!!!!!
The best thing for you to do is to make the request , when the response comes in then you call set state . When you call componentDidMount and set state the request does not come in immediately. So the best thing to do.
getItemShop = () => {
axios.get('https://fortniteapi.io/shop?lang=en', {
headers: {
Authorization: FORTNITE_IO
}
})
.then(res => {
this.setState({itemShop: res.data})
}
.catch(err => err);
}
Remove console.log(this.state) and use the React devtools extension to view state instead.

How to save data to firebase using react native?

I'm using https://github.com/expo-community/expo-firebase-starter as a starter template to build a react native app using firebase.
I am working with the following file in Home.js and want to save data to firebase but am getting an error. The error.
firebase.database is not a function. (In 'firebase.database(reflection)', 'firebase.database' is undefined)
Here is the code I'm using. When someone writes a reflection, I'm trying to save that reflection text along with the user ID.
import React, {useEffect, useState } from "react";
import { StyleSheet, Text, View } from "react-native";
import { Container, Content, Header, Form, Input, Item, Label } from 'native-base';
import { Button } from "react-native-elements";
import { withFirebaseHOC } from "../config/Firebase";
import * as firebase from 'firebase';
import "firebase/database";
function Home({ navigation, firebase }) {
const [reflection, setReflection] = useState('');
const[member, setMember] = useState('');
useEffect(() => {
try {
firebase.checkUserAuth(user => {
if (user) {
// if the user has previously logged in
setMember(user);
console.log(member);
} else {
// if the user has previously logged out from the app
navigation.navigate("Auth");
}
});
} catch (error) {
console.log(error);
}
}, []);
async function postReflection() {
try {
await console.log(reflection);
await console.log(member.email);
firebase.database(reflection).ref('Posts/').set({
reflection,
}).then((data)=>{
//success callback
console.log('data ' , data)
}).catch((error)=>{
//error callback
console.log('error ' , error)
})
} catch (error) {
console.log(error);
}
}
async function handleSignout() {
try {
await firebase.signOut();
navigation.navigate("Auth");
} catch (error) {
console.log(error);
}
}
return (
<Container style={styles.container}>
<Form>
<Item floatingLabel>
<Label>Reflection</Label>
<Input
autoCapitalize='none'
autoCorrect={false}
onChangeText={text => setReflection(text)}
/>
</Item>
<Button style = {{ marginTop: 10, marginHorizontal:30 }}
title="Share"
rounded
onPress= {postReflection}
>
</Button>
</Form>
<Button
title="Signout"
onPress={handleSignout}
titleStyle={{
color: "#F57C00"
}}
type="clear"
/>
</Container>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
// justifyContent: "center"
}
});
export default withFirebaseHOC(Home);
Your /config/Firebase/firebase.js doesn't have a database property. Have a look at how the Firebase object is being exported.
// inside /config/Firebase/firebase.js
import "firebase/database"; // add this
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const Firebase = {
// add this
database: () => {
return firebase.database()
}
};
export default Firebase;
Have a read of this step. You can't just import the part of the firebase library, you need to actually assign it to a variable and export it to use it.
https://firebase.google.com/docs/web/setup#namespace
Add the following after import * as firebase from 'firebase';
import "firebase/database";
Each Firebase product has separate APIs that must be added, as described in the documentation.

Categories

Resources