Error when I was trying to render a map of items - javascript

I am trying to figure out where my error is in my react js page
I have tried different things like changing it into a state component, return and render statements, etc. But its still giving me
"TypeError: Cannot read property 'map' of undefined
Recipes
src/components/Recipes.js:4
1 | import React from "react";
2 |
3 | const Recipes = (props) => (
4 |
5 | { props.recipes.map((recipe)=> {
6 | return (
7 |
View compiled"
App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import InputForm from "./components/InputForm";
import Recipes from "./components/Recipes"
const API_KEY= "mykey";
class App extends Component {
state= {
recipes: []
}
getRecipe = async (e) => {
e.preventDefault();
const recipeName = e.target.elements.recipename.value;
const api_call = await fetch(`https://www.food2fork.com/api/search?key=${API_KEY}&q=${recipeName}&page=2`)
const data = await api_call.json();
this.setState({ recipes: data.recipes });
}
render() {
return (
<div className="App">
<header className="App-header">
React Cookbook
</header>
<InputForm getRecipe={this.getRecipe} />
<Recipes recipes={this.state.recipes} />
</div>
);
}
}
export default App;
Recipes.js
import React from "react";
const Recipes = (props) => (
<div>
{ props.recipes.map((recipe)=> {
return (
<div key={recipe.recipe_id }>
<img src={recipe.image_url} alt={recipe.title}/>
<h3>{ recipe.title }</h3>
</div>
)
})}
</div>
)
export default Recipes;

As Andrew notes in the comments, it sounds like the response from the server is undefined, and that's what is getting added to the recipes state object. You can check for this in the console. Are your API key and recipe name valid, for example? Are you accessing the correct part of the returned data?
As an aside, recipes in state is empty on the first render. You need to check for that possibility in your code. Here I've simply returned an empty div, but you could add a loading spinner or something there instead to provide useful feedback to the user.
render() {
const { recipes } = this.state;
if (!recipes.length) return <div />;
return (
<div className="App">
<header className="App-header">
React Cookbook
</header>
<InputForm getRecipe={this.getRecipe} />
<Recipes recipes={recipes} />
</div>
);
}

Related

React: Passing Props not working. What am I missing?

as you may get from the title, passing props in react is not working. And i donĀ“t get why.
Main Ap Component
import './App.css';
import Licence from './Licence';
function App() {
return (
<>
<Licence>
test={"Test123"}
</Licence>
</>
);
}
export default App;
Other Component
import React from 'react';
const Licence = (props) => {
return (
<div>
<h1>name : {props.test}</h1>
</div>
)
}
export default Licence;
Problem
if i start the script and render the page, nothing is shown. What am I doing wrong?
Licence component looks good to me!
All you have to do is change up how you set it up on App. Props need to be passed on the tag, like this:
import './App.css';
import Licence from './Licence';
function App() {
return (
<>
<Licence test={"Test123"} />
</>
);
}
export default App;
update your App component:
```
<Licence
test={"Test123"} />
```
Pass like this
<Licence test={"Test123"} />
and access like this
const Licence = (props) => {
return (
<div>
<h1>name : {props.test}</h1>
</div>
)
}
Another way
<Licence>
Test123
</Licence>
access like this
const Licence = (props) => {
return (
<div>
<h1>name : {props.children}</h1>
</div>
)
}

problem with rendering an object property from API object

I have requested API call in my Recipe App and have access to all the data I need in my front page but then when I try to to get specific properties from the API call in another page of my app I get an error once I try to render it.
I get an error telling me "Unable to get property 'label' of undefined or null reference"
could someone please help?
This is my code:
RecipeApp
import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Form from "./components/form";
import Recipes from "./components/Recipes";
import "./App.css";
export default class RecipeApp extends React.Component {
state = {
recipes: []
};
getRecipe = async event => {
event.preventDefault();
const recipeName = event.target.recipeName.value;
const API_CALL = await fetch(
`https://api.edamam.com/search?q=${recipeName}&app_id=${API_ID}&app_key=${API_KEY}&from=0&to=10&calories=591-722&health=alcohol-free`
);
const data = await API_CALL.json();
this.setState({
recipes: data.hits
});
console.log(this.state.recipes);
};
render() {
return (
<div className="App">
<header>
<h1>Find Your Recipe</h1>
</header>
<Form getRecipe={this.getRecipe} />
<Recipes
recipes={this.state.recipes}
/>
</div>
);
}
}
Router
import React from "react"
import { BrowserRouter, Switch, Route } from "react-router-dom";
import RecipeApp from "../recipe-app"
import Recipe from "./Recipe"
const Router = () => {
return (
<BrowserRouter>
<Switch>
<Route path="/" component={RecipeApp} exact/>
<Route path="/recipe/:label" component={Recipe} />
</Switch>
</BrowserRouter>
)
}
export default Router
Recipes
import React from "react"
import { Link } from "react-router-dom"
const Recipes = ({ recipes }) => (
<div id="container">
<div className="row">
{recipes.map( (item) => {
return(
<div key={item.recipe.label} className="col-md-4" style={{marginBottom: "2rem"}}>
<div id="item-box">
<img
src={item.recipe.image}
alt={item.recipe.label} />
<div id="item-text">
<h3>{item.recipe.label.length > 20 ? `${item.recipe.label}` : `${item.recipe.label.substring(0, 25)}...`}</h3>
<p><i>publisher: {item.recipe.source}</i></p>
</div>
<button>
<Link
to={ {
pathname: `/recipe/${item.recipe.label}`,
state: { recipe: item.recipe.label }
} }>view recipe
</Link>
</button>
</div>
</div>
)
})}
</div>
</div>
)
export default Recipes;
Recipe
import React from "react"
class Recipe extends React.Component {
state = {
activeRecipe: []
}
componentDidMount = async () => {
const title = this.props.location.state.recipe
const request = await fetch(
`https://api.edamam.com/search?q=${title}&app_id=${API_ID}&app_key=${API_KEY}&from=0&&calories=591-722&health=alcohol-free`
);
const response = await request.json();
this.setState({ activeRecipe: response.hits[0] })
}
render() {
const recipe = this.state.activeRecipe
console.log(recipe.recipe.label)
return(
<div></div>
)
}
}
export default Recipe
This is Error Message:
The above error occurred in the <Recipe> component:
in Recipe (created by Context.Consumer)
in Route (at Router.js:11)
in Switch (at Router.js:9)
in Router (created by BrowserRouter)
in BrowserRouter (at Router.js:8)
in Router (at src/index.js:7)
SCRIPT5007: SCRIPT5007: Unable to get property 'label' of undefined or null reference
main.chunk.js (115,5)
0: Unable to get property 'label' of undefined or null reference```
Because when component starts, the recipes state is = []. The API that you call to the server is Async. At the first time render of Component, this API still not yet return data for you, for the second time, you will got this data.
At here: {recipes.map( (item) => { })}, recipes empting in the first time render of Component, so when you access to item.recipe.label. You will got the error Unable to get property 'label' of undefined or null.
To resolve this, make sure recipes has data like this:
recipes.length > 0 && recipes.map( (item) => { ... })
Or you can use default parameter like this:
{recipes.map( (item) => {
const { recipe = {} } = item;
// use default parameter here to make sure recipe always is an object
// then, use recipe.label will be no errors
return(
<div key={recipe.label} className="col-md-4" style={{marginBottom: "2rem"}}>
...
</div>
)
})}

How to use a state from one class to another

So i'm currently working on a PokeDex using the PokeApi available online.
The code of the project is as follows:
import React, { Component } from "react";
import PokemonCard from "./PokemonCard";
import "../ui/PokemonList.css";
import axios from "axios";
export const PokemonList = class PokemonList extends Component {
state = {
url: "https://pokeapi.co/api/v2/pokemon/",
pokemon: null
};
async componentDidMount() {
const res = await axios.get(this.state.url);
this.setState({ pokemon: res.data["results"] });
console.log(res);
}
render() {
return <div></div>;
}
};
export const PokeList = () => {
return (
<React.Fragment>
{this.state.pokemon ? (
<section className="poke-list">
{this.state.pokemon.map(pokemon => (
<PokemonCard />
))}
</section>
) : (
<h1>Loading Pokemon</h1>
)}
</React.Fragment>
);
};
As you can see, I have declared a state in the PokemonList Component class, but then I try to call it further down within the variable PokeList. The issue is that the state is not being recognized in PokeList
(I get the error "TypeError: Cannot read property 'state' of undefined" )
How can I go about calling the state that's declared in the class above?
-------------------EDIT-------------------------------
Okay, so I realized something. I have a code for my Dashboard.js that displays my list. Code is as follows
import React, { Component } from "react";
import { PokeList } from "../pokemon/PokemonList";
export default class Dashboard extends Component {
render() {
return (
<div>
<div className="row">
<div className="col">
<PokeList />
</div>
</div>
</div>
);
}
}
When I change the code from PokeList to PokemonList. so it'd be
import React, { Component } from "react";
import { PokemonList } from "../pokemon/PokemonList";
export default class Dashboard extends Component {
render() {
return (
<div>
<div className="row">
<div className="col">
<PokemonList />
</div>
</div>
</div>
);
}
}
I think get a list of 20 pokemon from the Api from
console.log(this.state.pokemon);.
But since I'm not displaying PokeList on the dashboard, then none of the pokemon cards display.
Screenshot of console output
First of all functional components are stateless. If you need to maintain state use class components or hooks. You can't use the state of one component in another component, You have two options,
Create a parent-child relationship between those components
Use state management libraries(Redux, etc)
There's a little of confusion between your PokemonList and PokeList component. I believe that what you really are looking for is to have just one of those. If you mix the two, you can have a component that controls the view based on the state, in your case, the state is your Pokemon list.
I mixed the two here, so your render method renders "Loading Pokemon" until you get your response back from axios, then when the response is back, it gets that data, updates your state and the state update trigger a re-render.
import React, { Component } from "react";
import PokemonCard from "./PokemonCard";
import axios from "axios";
class PokemonList extends Component {
state = {
url: "https://pokeapi.co/api/v2/pokemon/",
pokemon: null
};
componentDidMount() {
axios.get(this.state.url).then(res => {
this.setState({ pokemon: res.data["results"] });
});
}
render() {
let pokemonList = <h1>Loading Pokemon</h1>;
const pokemons = this.state.pokemon;
if (pokemons) {
pokemonList = (
<section className="poke-list">
<ul>
{pokemons.map(pokemon => (
<PokemonCard pokemon={pokemon} />
))}
</ul>
</section>
);
}
return <React.Fragment>{pokemonList}</React.Fragment>;
}
}
export default PokemonList;
I also created a simple PokemonCard component where I list the result from the API, just to show you that that approach works.
import React from "react";
const pokemonCard = props => {
return (
<li key={props.pokemon.name}>
<a href={props.pokemon.url}>{props.pokemon.name}</a>
</li>
);
};
export default pokemonCard;
You can find the final code, with PokeList and PokemonList now combined into one component called PokemonList here:
Keep in mind that if your render function depends on a certain state, it's probably certain that you should have that state being managed in that component, or passed down from a parent component.
In your example, I noticed you set url inside your state. URL is really not something that will change. It's a constant,so you can easily remove that from your state and place it in a variable and just leave your pokemon list there.
For example:
const url = "https://pokeapi.co/api/v2/pokemon/";
state = {
pokemon: null
};
componentDidMount() {
axios.get(url).then(res => {
this.setState({ pokemon: res.data["results"] });
});
}
import React , { Component } from "react";
import axios from "axios";
//make it as class based component
export default class PokemonList extends Component {
state = {
url: "https://pokeapi.co/api/v2/pokemon/",
pokemon: null
};
async componentDidMount() {
const res = await axios.get(this.state.url);
this.setState({ pokemon: res.data["results"] });
console.log(res);
}
render() {
//check your data here
console.log(this.state.pokemon)
{/*pass data to child*/}
return <div> <PokeList data = { this.state } /> </div>;
}
};
//export this component
export const PokeList = (props) => {
//check your data is coming or not
console.log(props.data)
//access your data from props
return (
<React.Fragment>
{props.data.pokemon ? (
<section className="poke-list">
{props.data.pokemon.map(pokemon => (
pokemon.name
))}
</section>
) : (
<h1>Loading Pokemon</h1>
)}
</React.Fragment>
);
};
You need iterate your your pokelist passing the result from your componentDidMount function to your child component as a prop , then receive your prop in the child component here it's a working codesandbox iterating your pokemon names in the pokeList child component

JavaScript object function in react component class

I got the object function using in react component, the below is my code, I tried to create an object function inside articleActions object, not got the syntax error. The api import is working fine and I get the right data and store in this component state: this.state.articles, this.state.authors.
App.js
import React from "react";
import DataApi from "../DataApi";
import data from "../testData";
import ArticleList from "./ArticleList";
const api = new DataApi(data.data);
class App extends React.Component {
constructor() {
super();
this.state = {
articles: api.getArticles(),
authors: api.getAuthors()
};
}
articleActions = {
lookupAuthor: authorId => this.state.authors[authorId]
};
render() {
return (
<ArticleList
articles={this.state.articles}
articleActions={this.articleActions}
/>
);
}
}
export default App;
the second file: ArticleList.js
import React from "react";
import Article from "./Article";
const ArticleList = props => {
return (
<div>
{Object.values(props.articles).map(article => (
<Article
key={article.id}
article={article}
actions={props.articleActions}
/>
))}
</div>
);
};
export default ArticleList;
the third file: Article.js
import React from "react";
const Article = props => {
const { article, actions } = props;
const author = actions.lookupAuthor(article.authorId);
return (
<div>
<div>{article.title}</div>
<div>{article.date}</div>
<div>
<a href={author.website}>
{author.firstName} {author.lastName}
</a>
</div>
<div>{article.body}</div>
</div>
);
};
export default Article;
The error message is :
SyntaxError: C:/Users/coral/Documents/react-advanced/lib/components/App.js:
Unexpected token (16:17)
14 | };
15 | }
> 16 | articleActions = {
| ^
17 | lookupAuthor: authorId => this.state.authors[authorId]
18 | };
the lookupAuthor should be a function with parameter:authorId, and get the return value of the author object. this.state.authors is the array of author objects. Each object with the authorId as the key, and author object as the value. I am not sure what is the error here when declare the function inside the js object. Hope someone can help
That should be method:
articleActions = () => ({
lookupAuthor: authorId => this.state.authors[authorId]
});

React.js search bar always fetches the same content

I'm building a search engine with React.js, where I can look for GIPHY gifs using their API. Everytime I type a word(any word), it always loads the same gifs and when I erase and write another word, the gifs don't update.
index.js:
import React from 'react'; //react library
import ReactDOM from 'react-dom'; //react DOM - to manipulate elements
import './index.css';
import SearchBar from './components/Search';
import GifList from './components/SelectedList';
class Root extends React.Component { //Component that will serve as the parent for the rest of the application.
constructor() {
super();
this.state = {
gifs: []
}
this.handleTermChange = this.handleTermChange.bind(this)
}
handleTermChange(term) {
console.log(term);
let url = 'http://api.giphy.com/v1/gifs/search?q=${term.replace(/\s/g, '+')}&api_key=aOfWv08Of7UqS6nBOzsO36NDvwYzO6io';
fetch(url).
then(response => response.json()).then((gifs) => {
console.log(gifs);
this.setState({
gifs: gifs
});
});
};
render() {
return (
<div>
<SearchBar onTermChange={this.handleTermChange} />
<GifList gifs={this.state.gifs} />
</div>
);
}
}
ReactDOM.render( <Root />, document.getElementById('root'));
search.js
import React, { PropTypes } from 'react'
import './Search.css'
class SearchBar extends React.Component {
onInputChange(term) {
this.props.onTermChange(term);
}
render() {
return (
<div className="search">
<input placeholder="Enter text to search for gifs!" onChange={event => this.onInputChange(event.target.value)} />
</div>
);
}
}
export default SearchBar;
Giflist:
import React from 'react';
import GifItem from './SelectedListItem';
const GifList = (props) => {
console.log(props.gifs);
const gifItems = props.gifs && props.gifs.data && props.gifs.data.map((image) => {
return <GifItem key={image.id} gif={image} />
});
return (
<div className="gif-list">{gifItems}</div>
);
};
export default GifList;
GifItem:
import React from 'react';
const GifItem = (image) => {
return (
<div className="gif-item">
<img src={image.gif.images.downsized.url} />
</div>
)
};
export default GifItem;
I can't seem to find where is the issue here. Is it because of this.handleTermChange = this.handleTermChange.bind(this) and there is no "update" state after?
Any help is welcome :) Thanks!
Its because, you are not putting the term value entered by user in the url, all the time you hit the api with static value term, here:
'http://api.giphy.com/v1/gifs/search?q=${term.replace(/\s/g, '+')}&api_key=aOfWv08Of7UqS6nBOzsO36NDvwYzO6io';
Replace ' by ' (tick), like this:
let url = `http://api.giphy.com/v1/gifs/search?q=${term.replace(/\s/g, '+')}&api_key=aOfWv08Of7UqS6nBOzsO36NDvwYzO6io`;
Check MDN Doc for more details about Template Literals.

Categories

Resources