Trying to map on React - javascript

I added the Nutrition file
const Nutrition = () => {
return(
<div>
<p>Label</p>
<p>Quantity</p>
<p>Unit</p>
</div>
)
}
export default Nutrition
I'm trying to map something in React but I'm getting this error map is not function. I'm trying to fetch an Api and now I'm trying to map another component to it, but the error is still there. Could someone help me or give me a hint
const ApiNutrition = () => {
const [nutritions, setNutritions] = useState([])
useEffect( () => {
getNutritions();
}, [])
const getNutritions = async () => {
const response = await fetch(`https://api.edamam.com/api/nutrition-data?app_id=${API_ID}&app_key=${API_KEY}&ingr=1%20large%20apple`)
const data = await response.json();
setNutritions(data.totalNutrientsKCal)
console.log(data.totalNutrientsKCal);
}
return(
<div>
<form className="container text-center">
<input classname="form-control" type="text" placeholder="CALORIES"/>
<button classname="form-control" type="submit">Submit</button>
</form>
{nutritions.map(nutrition => (
<Nutrition />
))}
</div>
)
}
export default ApiNutrition

From your code, I can see you have two places where you are setting the value of nutritions. One is while defining with useState(), and the other is after API call with setNutritions.
The error you are getting is map is not a function, it means somehow type of nutritions is not an array.
while defining with useState you are providing [] as default value so it means the error is with the API, the response you are getting from API which you are passing to setNutritions is not an array.
You can debug the API response type by typeof data.totalNutrientsKCal inside console.log

Related

REACT - My onClick function isn't searching through any of the cities from the API

Here I am simply making a request. The request is successful and return an array of different breweries along with cities plus more info. The useEffect does not set the default search for a new york city, instead I get a the initial array rendered from the first call.
import React, {useState, useEffect} from 'react';
import '../styles/searchPage.css'
import SearchCard from '../components/SearchCard';
const API_URL = 'https://api.openbrewerydb.org/breweries?by_city&per_page';
function SearchPage() {
const [cards, setCards] = useState([]);
const [searchTerm, setSearchTerm] = useState('');
const searchRestaurants = async (city) => {
const req = await fetch(`${API_URL}&s=${city}`);
const data = await req.json()
console.log(data)
setCards(data)
}
useEffect(() => {
searchRestaurants('new york')
}, [])
Here is how I set up my search. I set the searchTerm onChange event to read the value typed.
Inside of my button I have an onClick function which should fire the restaurant search with any search term in it. Instead i'm receiving back the initial array that I get from the first call to api.
return (
<div className='search'>
<h1>Enter a City or Town name</h1>
<div className='search-container'>
<input
type="text"
name="search"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
onKeyPress={(e) => {
if (e.key === 'Enter'){
searchRestaurants(searchTerm);
}
}}
placeholder="Search..."
class="search-input"
/>
<button
className='next'
onClick={()=> searchRestaurants(searchTerm)}
>Go</button>
</div>
Checked your code.
And checked API documentation and i found that you using API incorrectly.
I would change API_URL from https://api.openbrewerydb.org/breweries?by_city&per_page to https://api.openbrewerydb.org/
API_URL - Url defined incorrectly,you did assign endpoint url with 2 empty parameters by_city & per_page which are being sent empty.
Now to fix your issue and properly use endpoint URL should be updated.
From fetch(${API_URL}&s=${city}); to fetch(${API_URL}/breweries?by_city=${city});
Hope it helps!

How to read array document field from firebase firestore (React js)

Hi I am trying to get todo array field from cloud firestore database in a react project. When i print out with console log I can see the empty array symbol but It throws error at the same time and does not render the page.
This is the Firestore.js file to get data from firebase.
export const userTodoList = async (email) => {
await onSnapshot(doc(db, "users", email), (doc) => {
console.log(doc.data().todos);
return doc.data().todos;
});
};
This the MainPage.js file to get the array and pass to CardList component.
const MainPage = () => {
const todoArray = userTodoList(auth.currentUser.email);
const [todos, setTodos] = useState(todoArray);
return (
<div>
<section>
<NavBar></NavBar>
<ToDoForm />
</section>
<section>
<CardList array={todos} />
</section>
</div>
);
};
This is the CardList component to render the cards with the array mapping. I am checking for if the array length is 0 or not but still get errors.
const CardList = (props) => {
const array = props.array;
if (array.length === 0) {
return (
<div className="grid_container">
<h2>Found no todos</h2>
</div>
);
}
return (
<div className="grid_container">
{array.map((todo) => (
<Card title={todo.title} />
))}
</div>
);
};
Errors.
The object.map is not a function error occurs because the map method is not implemented on objects. To iterate over an object, use the Object.keys() method to get an array of the object's keys and call the map()method on the array of keys.
I.e You can use Object.keys() or Object.entries() and then use map
For example:
array.keys(obj).map(key => {
//other statements
});
For more details you can check this article

get array from single firestore document with ReactJs

I'm learning to use firebase and react. I have shared my firestore collection image. and my code for fetching the array from my document is given below.
This code is fetching the data from my firestore database and then storing the result in my watchlistMovies react state. when i try to log the react state or even data.data() it gives the desired result but when i try to map over the array or do something similar like logging watchlistMovies.myList[0].media_type it hits me with an error. i tried my best trying different things making it work but it breaks a thing or two in process.
I hope someone here will help me. Thank you in advance! : )
updated the code
const Watchlist = () => {
const [watchlistMovies, setwatchlistMovies] = useState([]);
const {currentUser} = useAuth()
const usersCollectionRef = collection(db,"users")
const docRef = doc(db,"users",currentUser.uid)
useEffect(() => {
const getWatchListMovies = async () => {
const data = await getDoc(docRef)
if (data.exists()) {
console.log(data.data());
setwatchlistMovies([...watchlistMovies ,data.data().myList])
} else {
console.log("empty");
}
}
getWatchListMovies();
}, [])
console.log(watchlistMovies);
// console.log(watchlistMovies.myList[0]);
return (
<div className="content-page-area">
<h1 className="trending-text"> My Watchlist </h1>
<Container className="watchlist-container">
<hr/>
{watchlistMovies.map(
(item) => (
<ListContent
item_poster={item.poster_url}
item_title={item.media_title}
item_year={item.release_year}
item_rating={item.media_rating}
item_type={item.media_type}
item_id={item.media_id}
/>
)
)}
</Container>
<br/>
<br/>
<br/>
</div>
)
}
export default Watchlist

cannot read property of map undefined react

I am a newbie react learner and here trying to make an api call to display list of weather details(for test case I am trying to get "app_max_temp") but I am getting error as "cannot read property of map undefined at SearchCity(SearchCity.js:29)" .I have tried that url in postman and works absolutely fine giving response data. I have my code below. I can't figure out what is wrong and how to solve it. Any help would be appreciated. Thanks in advance.
import React,{useState} from 'react';
export default function SearchCity(){
const[query,setQuery] = useState('');
const[weatherResponse,setWeatherResponse] = useState([]);
const searchCity = async (e) =>{
e.preventDefault();
const api_key ="YourApiKey";
const url = `https://api.weatherbit.io/v2.0/forecast/daily?city=${query}&key=${api_key}`;
try{
const res = await fetch(url);
const data = await res.json();
console.log(data.results);
setWeatherResponse(data.results);
}
catch(error){
console.error(error);
}
}
return(
<>
<form className="form" onSubmit={searchCity}>
<label className="cityTitle" htmlFor="query">City Name : </label>
<input type="text" value={query} name="query" onChange={(e)=>setQuery(e.target.value)} />
<button className="btnSearch" type="submit">Search</button>
</form>
{weatherResponse.map(res=>(
<p>{res.app_max_temp}</p>
)
)}
</>
)
}
Weatherbit 16 Day Forecast API Documentation
Weatherbit 16 Day Forecast Swagger UI
The API returns those values in property data, not result:
console.log(data.data);
setWeatherResponse(data.data);
Make sure you have a proper API key (don't post it on here of course).

react map is not a function error in my app

I am a beginner in ReactJS and I am getting an error that I don't understand. This is my first written with ReactJS app. Here is my code.
Error
react map is not a function error in my app
SearchBar Component
import RecipeList from './recipes_list';
class SearchBar extends Component {
state = {
term : []
}
onInputChange(term){
this.setState({term});
}
onSubmit = async (term) => {
const recName= this.state.term;
term.preventDefault();
const api_key = 'a21e46c6ab81bccebfdfa66f0c4bf5e9';
const api_call = await Axios
.get(`https://www.food2fork.com/api/search?key=${api_key}&q=${recName}&`)
.then(res=> {this.setState({term : res.data.recipes})})
}
render() {
return (
<div>
<form onSubmit={this.onSubmit} >
<div className="search-bar">
<input
type="text"
value={this.state.term}
onChange={event => this.onInputChange(event.target.value)}
/>
<button type="submit">Search</button>
</div>
</form>
<RecipeList List ={this.state.term}/>
</div>
)
}
}
RecipeList Component
const RecipeList = props => (
<div>
{
props.List.map((recipe) => {
return (
<div>{recipe.title}</div>
)
})
}
</div>
)
export default RecipeList;
Thank you guys for your help
Your problem is in this snippet:
onInputChange(term){
this.setState({term});
}
This will set your state variable to a String. For example, if I type in Hello!, your state object will be { term: 'Hello!' }. You're now trying to .map() over a String, String.map is not a function.
The .map function is only available on array.
It looks like data isn't in the format you are expecting it to be (it is {} but you are expecting []).
this.setState({data: data});
should be
this.setState({data: data.conversations});
Check what type "data" is being set to, and make sure that it is an array.
More generally, you can also convert the new data into an array and use something like concat:
var newData = this.state.data.concat([data]);
this.setState({data: newData})
This pattern is actually used in Facebook's ToDo demo app (see the section "An Application") at https://facebook.github.io/react/.

Categories