i'm building a pokedex (pokemon index) using an api called pokeapi. I decided to use this wrapper to make things a little easier: https://github.com/PokeAPI/pokedex-promise-v2
I have a input field and when the submit button is clicked, I want the api to return the pokemon if there is a match.
Searchbar.js:
onClick() {
var text = this.state.text;
PokeApi.getPokemon(text).then(function(data) {
console.log(data);
}.bind(this));
}
api.js:
import React, { Component } from 'react';
import Pokedex from 'pokedex-promise-v2';
var P = new Pokedex();
var PokeApi = {
getPokemon: function(query) {
P.getPokemonByName(query)
.then(function(response) {
return response;
})
.catch(function(error) {
console.log('There was an ERROR: ', error);
});
}
}
export default Component
Now when I click on submit, I get the following in console:
Uncaught TypeError: _api2.default.getPokemon is not a function
I can't seem to figure out what '_api2.default' is or how to get pass this issue. If anyone could provide some assistance it would be greatly appreciated, thanks!
Your code sample doesn't appear to be complete but you probably need to export the PokeApi object and import it where you plan to use it.
(Perhaps you intended to export PokeApi from api.js rather than re-exporting React.Component?)
We use Pokeapi for get all data about Pokemon.
Here is list of all Pokemon.
http://pokemongotech.com/pokemongo-pokedex-newswoof1orderbyid?swoof=1&orderby=id
Related
I'm recreating a simple weather app with react and am having a lot of trouble creating a very simple API call. I've tried a plethora of methods on here, youtube, etc and continuously get errors. The current code I have is:
import Axios from 'axios';
import { Home } from '../components/Home'
import React, {useState, useEffect} from 'react'
var weatherApiRootUrl = 'https://api.openweathermap.org';
var weatherApiKey = 'd91f911bcf2c0f925fb6535547a5ddc9';
//function to generate weather URL. fetches lat/lon and creates new url
function GetWeatherUrl(loc){
const [weatherLink, setWeatherLink] = useState("");
const getCoordinates = () => {
Axios.get(`${weatherApiRootUrl}/geo/1.0/direct?q=${loc}&limit=5&appid=${weatherApiKey}`).then(
(response)=>{
console.log(response);
setWeatherLink(`${weatherApiRootUrl}/data/2.5/onecall?lat=${response.data.lat}&lon=${response.data.lon}&units=imperial&exclude=minutely,hourly&appid=${weatherApiKey}`);
}
);
};
return(
<div>
{weatherLink}
</div>
);
}
export{
GetWeatherUrl
}
The purpose of this file is just to use the user input (a city name designed by variable loc) to fetch lat/lon coordinates of the inputted city as that data is needed for the second link that fetches weather information. The user input is handled from another component and works fine.
All I intend for this code to do is fetch latitude and longitude data using loc and use those numbers to generate the new link that fetches weather data. The weather data will be done with a different api call on another file. The working method of this current file should be useable for the future file meant to fetch weather so this is kind of two birds in one stone.
I need the weatherLink generated to be able to be exported to do this so I would really prefer a solution allowing that please. I originally was going to just export the raw lat/lon data and use them for the call in the new file as how I did with loc here but I decided returning a completed link as a string would maybe be easier. Really would appreciate someone's help on this it's been frustrating me for way longer than it should!
Not really needed but here's the non-react version of the site if it helps: https://giovannimalcolm.github.io/weather-dashboard/
This can be easily solved without needing to use React at all, since it is not a component and doesn't have any rendering logic in itself per se:
import Axios from 'axios';
const weatherApiRootUrl = 'https://api.openweathermap.org';
const weatherApiKey = 'd91f911bcf2c0f925fb6535547a5ddc9';
export async function GetWeatherUrl(loc) {
const response = await Axios.get(`${weatherApiRootUrl}/geo/1.0/direct?q=${loc}&limit=5&appid=${weatherApiKey}`);
return `${weatherApiRootUrl}/data/2.5/onecall?lat=${response.data.lat}&lon=${response.data.lon}&units=imperial&exclude=minutely,hourly&appid=${weatherApiKey}`;
}
Then in places where you need to use the weather URL, you need to remember that GetWeatherUrl returns a promise, so you've got to await it (or handle it like any other promise):
const myFn = async () => {
const weatherUrl = await GetWeatherUrl(loc);
const weatherUrlData = await Axios.get(weatherUrl);
};
myFn();
I have recently been trying to create a web app with NextJS. I know some basics in web development but I was a little lost when using NextJS as I didn't do any React either before.
I've tried fetching data from an API and using this data in my page. I struggled a bit but in the end I got it working with the help of getServerSideProps.
My question is, how could I use getServerSideProps multiple times in my application so that I can fetch many other routes ? I've tried using getServerSideProps in a different file, using its response in a function that I then export as a component and use it so I can "get components of getServerSideProps responses" if it makes sense, but had many different errors when trying to do so.
Could someone explain how it actually works and how I could resolve my issue, and if it doesn't work that way, how could I make it work?
Here's an example using Coinbase's API :
import { useState } from 'react'
import fetch from 'isomorphic-fetch'
export const getServerSideProps = async () => {
const res = await fetch('https://api.coinbase.com/v2/prices/ETH-USD/buy')
const data = await res.json()
return {
props: {
ethprice: data
}
}
};
I then use "ethprice" in my Home function such as :
export default function Home({ ethprice }) {
return (
[page content, divs, text etc...]
{etherprice.data.amount}
Thanks!
getServerSideProps is specific to that particular file, you can't just use it in any way you want.
const Example = (props) => {
return // this is your component
}
export const getStaticProps = async () => {
// this will provide props specifically for 'Example'
}
More than that getStaticProps will only be run once on static page generation and never again, along with fetching the props for that particular component only. So you can't get live data from it, only data required to generate the page (like page title).
You can have a look at getServerSideProps if you're looking for something more dynamic that can fetch props at runtime. After that you can pass those props down to children if you need to.
I am fairly new to react and I was experimenting on axios get requests . So What I am trying to do is that I have a json file in my public folder and I am making a get axios request to the location of that file and then I am printing the result in an array .
The first method worked pretty smoothly . A demo of the function is given below
The output is given below:
And as evident , this approach worked pretty fine.
However I also made a class named Fetch inside a service.js file . This class had a method named fetch which used axios to make a get request.
The demo of this class is given below:
import React from 'react';
import axios from "axios";
class Fetch extends React.Component
{
constructor()
{
super();
}
fetch()
{
console.log("Hi i am in fetch of service....");
axios.get('./config.json').then(response=>{
var x=response.data;
console.log("----------------------------------------->"+JSON.stringify(x));
return x;
},(err)=>{
return err;
})
}
}
export default Fetch;
I imported this class in another js file and made an object of this class to call the fetch method.A demo of my usage is given below:
However when I tried to do this , I got the following error:
What am I doing wrong ? If it worked for the first time , then why is this not working now?
You are receiving that error because nothing is returned from Fetch.fetch(), let alone a promise.
You are trying to call .then() on a void function, so you will not be able to access the response.
In your Fetch class, return the axios request from the fetch() function:
fetch() {
return axios.get('/config.json').then(response => {
// your code
})
}
I try to load the ID from a ble device via AsyncStorage that I save in a another component. But then I do this I get the following error:
ExceptionsManager.js:65 Cannot read property 'loadMac' of undefined
This is my loadMac() function:
export function loadMac() {
AsyncStorage.getItem(MAC_KEY)
.then((item) => {
console.log(item);
return item;
})
.catch((error) => {
console.log(error);
});
}
And I call this function in my component like this:
store.loadMac();
Then I try
AsyncStorage.getItem(MAC_KEY)
.then((item) => {
console.log(item)});
I will get my ID.. but not from my function that I have in another file.
Any solution ?
The error message says store is not defined, so you should look for a solution checking it.
By the code you posted I am assuming you've tried to have 2 different components: one stateless component named 'store' which you are exporting to access its' loadMac function. And another where you are importing the 'store' component. Correct me if I'm wrong.
If this is the case, your export syntax is incorrect. It should be something similar to this
export default const Store = () => {...}
And then import it like this:
import Store from './yourPathToStore';
If it's not, then you shouldn't have that export and also clarify what is exactly your 'store'.
Hope it helps.
I am using peerjs library to build a chat. I'm trying to do an observable to trigger an event every time I get a new message.
this.data = new Observable(observer => {
this.peer.on('connection', (data) => {
alert("TRIGGER");
observer.next(data);
});
})
this.peerMessages = this.data.subscribe(message => {
alert(message);
});
I can see the first alert but the second one never triggers. I don't get any error from the browser console. What am I doing wrong?
Im trying to use an observer because instead of alert(message) I want to change a variable from the angular component.
The code looks good, but make sure you import everything you need. For example, if using rxjs:
import { Observable, ... } from 'rxjs/Observable';