I keep getting this error that map is not defined. I changed my code around because of a regeneratorRuntime error and now I'm stuck with this one. Any help is appreciated!
import React, {Component, useEffect, useState} from 'react'
import axios from 'axios'
require("regenerator-runtime/runtime");
const App = () => {
const [data, setData] = useState({heroes: []});
useEffect(() => {
const fetchData = async () => {
const result = await axios(
'https://api.opendota.com/api/heroStats',
);
setData(result.data);
};
fetchData();
}, []);
return(
<ul>
{data.heroes.map(item => (
<li key={item.id}>
<a href={item.name}>{item.localized_name}</a>
</li>
))}
</ul>
)
};
export default App
Define like this
setData({...data, heroes:result.data});
because you have pass heroes array variable to state so spread variable then set data
useEffect(() => {
const fetchData = async () => {
const result = await axios(
'https://api.opendota.com/api/heroStats',
);
setData({...data, heroes:result.data});
};
fetchData();
}, []);
The data returned from that API is just an array of objects. There is no key 'heroes'. So just do: data.map(item =>... and you should be good.
it'll working:
import React, {Component, useEffect, useState} from 'react'
import axios from 'axios'
require("regenerator-runtime/runtime");
const App = () => {
const [data, setData] = useState({heroes: []});
useEffect(() => {
// Using an IIFE
( async () => {
const result = await axios(
'https://api.opendota.com/api/heroStats',
);
setData({...data, heroes: result.data || [] });
})();
}, []);
return(
<ul>
{data.heroes.map(item => (
<li key={item.id}>
<a href={item.name}>{item.localized_name}</a>
</li>
))}
</ul>
)
};
export default App
{data.heroes && data.heroes.map(item => (...
Will this work?
The .map function is only available on array.
Check what type "data" is being set to, and make sure that it is an array.
Here, the heros data is not set to "data" so you need to add to "Data"
you can do by using setData({...data, heroes:result.data});
this will work for you!
Related
How to get the data correctly
import { NextApiHandler } from "next";
import data from "../../../lib/data.json";
const cars: NextApiHandler = (_req, res) => {
res.status(200).json(data);
};
export default cars;
I tried to use async await for getting data but something went wrong. When I`m trying to print in console.log what is "cars" it returns me function instead of promise.
You can try this way to get data
import React, { useEffect, useState } from 'react';
import Item from '../Item/Item';
const Items = () => {
const [items, setItems] = useState([]);
useEffect( ()=>{
fetch('http://localhost:5000/items')
.then(res => res.json())
.then(data => setItems(data));
}, [])
return (
<div id='items' className='container'>
<h1 className='item-title'>Items For You</h1>
<div className="items-container">
{
items.map(item => <Item
key={item._id}
item={item}
>
</Item>)
}
</div>
</div>
);
};
export default Items;
What i'm trying to do:
Have some practice with fetching data in react, and i used a covid19 api with number of cases etc...
Here's the code :
import { useState, useEffect } from "react";
import axios from "axios";
const Home = () => {
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
const result = await axios("api_here",);
setData([result.data]);
};
fetchData();
}, [])
console.log(data);//i have a screen-shot below for the output
return (
<ul>
{data.map((items, index) => (
<li key={index}>{JSON.stringify(items)}</li>
//<li key={index}>{items}</li> This doesn't work
))}
</ul>
)} export default Home;
The problem is that the data is an array of 1 element, image here:
And data.map is iterating only on json[0] but i need to iterate over every country from the json.
I tried doing something like :
setData([result.data][0])
//or
data[0].map......
But doesn't work
A picture with the json data:
Your data is a map of key -> value so to iterate over all countries (keys).
<ul>
{Object.keys(data).map((key, index) => (
<li key={index}>{JSON.stringify(data[key])}</li>
))}
</ul>
You can Convert the Object of Objects to Array of Objects.
import { useState, useEffect } from "react";
import axios from "axios";
const Home = () => {
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
const result = await axios("api_here",);
let res = [result.data];
res = Object.entries(res[0]).map((e) => ( { [e[0]]: e[1] } ));
setData(res);
};
fetchData();
}, [])
console.log(data);
return (
<ul>
{data.map((items, index) => (
<li key={index}>{JSON.stringify(items)}</li>
//<li key={index}>{items}</li> This doesn't work
))}
</ul>
)} export default Home;
So, this a weird problem. Yesterday everything was working fine, I could see the category object displayed, I could switch between categories, but today I wanted to continue the project, but the data is not being displayed, I can not even see the object in the console. What could be the problem, is it in the Fetch I would really really appreciate the help
import React, {useState, useEffect} from 'react'
import URL from '../utilis/URL'
const BookContext = React.createContext();
export default function BooksProvider({ children }) {
const [data, setData] = useState([])
const [currentSelectedCategory, setCurrentSelectedCategory] = useState([]);
const handleSelectCategory = (category) => {
setCurrentSelectedCategory(data[category]);
};
const fetchData = async () => {
const response = await fetch(URL);
const result = await response.json();
console.log(data.result)
setCurrentSelectedCategory(result[Object.keys(result)[0]]);
setData(data);
};
useEffect(()=>{
fetchData();
},[])
return (
<BookContext.Provider value={{ data, handleSelectCategory, setCurrentSelectedCategory, currentSelectedCategory }}>
{children}
</BookContext.Provider>
);
}
export {BookContext, BooksProvider}
import React,{useState, useEffect} from 'react'
import './Home.css'
import Books from './Books'
import { BookContext } from "../../context/books";
const Home = () => {
const {data, handleSelectCategory, currentSelectedCategory } =React.useContext(BookContext)
return (
<div className='books__container' >
<h1 className='categories'>Categories</h1>
{Object.keys(data).map((key, index)=>{
let books = data[key];
return (
<>
<span key={key} onClick={() => handleSelectCategory(key)} className='books__list' >
{books[0].category}
</span>
</>
);})}
<Books category={currentSelectedCategory} />
</div>
)
}
export default Home
This doesn't do anything:
console.log(data.result)
Because data is an empty array (and arrays have no result property anyway):
const [data, setData] = useState([])
And this doesn't do anything:
setData(data);
Because you're just updating the state to itself, which changes nothing and probably doesn't trigger any re-render. (Though even if it does, the render is mapping the elements of data which is still an empty array.)
You probably meant to set the data state object to the result from the API?:
setData(result);
I am using firebase firestore and i fetched the data , everything is working fine but when i am passing it to some component only one item gets passed but log shows all the elements correctly.
I have just started learning react , any help is appreciated.
import React, { useEffect, useState } from 'react'
import { auth, provider, db } from './firebase';
import DataCard from './DataCard'
function Explore() {
const [equipmentList, setEquipments] = useState([]);
const fetchData = async () => {
const res = db.collection('Available');
const data = await res.get();
data.docs.forEach(item => {
setEquipments([...equipmentList, item.data()]);
})
}
useEffect(() => {
fetchData();
}, [])
equipmentList.forEach(item => {
//console.log(item.description);
})
const dataJSX =
<>
{
equipmentList.map(eq => (
<div key={eq.uid}>
{console.log(eq.equipment)}
<p>{eq.equipment}</p>
</div>
))
}
</>
return (
<>
{dataJSX}
</>
)
}
export default Explore
You have problems with setting fetched data into the state.
You need to call setEquipments once when data is prepared because you always erase it with an initial array plus an item from forEach.
The right code for setting equipment is
const fetchData = async () => {
const res = db.collection('Available');
const data = await res.get();
setEquipments(data.docs.map(item => item.data()))
}
The following code gives me a warning that
React Hook useEffect has a missing dependency: 'getData'.
Either include it or remove the dependency array
I know in the new rules of react I must wrap it in a useCallBack but I am unsure how to do so. Can someone please provide me with how to use, useCallBack properly. Thank you in advance!!
import React, { useState, useEffect, useCallback } from "react"
import axios from "axios"
const Home = () => {
const [data, setData] = useState(null)
const [query, setQuery] = useState("reacthooks")
useEffect(() => {
getData()
}, [query])
const getData = async () => {
const response = await axios.get(
`http://hn.algolia.com/api/v1/search?query=${query}`
)
setData(response.data)
}
const handleChange = event => {
event.preventDefault()
setQuery(event.target.value)
}
return (
<div>
<input type='text' onChange={handleChange} />
{data &&
data.hits.map(item => (
<div key={item.objectID}>
{item.url && (
<>
<a href={item.url}>{item.title}</a>
<div>{item.author}</div>
</>
)}
</div>
))}
</div>
)
}
export default Home
I would simply add the getData function into useEffect hook in your case instead.
Try the following:
useEffect(() => {
const getData = async () => {
const response = await axios.get(
`http://hn.algolia.com/api/v1/search?query=${query}`
)
setData(response.data)
}
getData()
}, [query])
I hope this helps!