it doesn't show an error and the project works just fine. I can log the data to the console as well. but it doesn't display in the UI. this is a tutorial project on youtube
I'm getting data from the API and passing that to the tours and tour components. and Tour component displays the fetched data.
App component
import React, { useState, useEffect } from "react";
import Loading from "./Loading";
import Tours from "./Tours";
// ATTENTION!!!!!!!!!!
// I SWITCHED TO PERMANENT DOMAIN
const url = "https://course-api.com/react-tours-project";
function App() {
const [loading, setLoading] = useState(true);
const [tours, setTours] = useState([]);
const fetchTours = async () => {
try {
const response = await fetch(url);
const tours = await response.json();
setLoading(false);
setTours(tours);
} catch (error) {
setLoading(true);
console.log(error);
}
};
useEffect(() => {
fetchTours();
}, []);
if (loading) {
return (
<main>
<Loading />
</main>
);
}
return (
<main>
<Tours tours={tours} />
</main>
);
}
export default App;
Tours component
import React from "react";
import Tour from "./Tour";
const Tours = ({ tours }) => {
return (
<section>
<div className="title">
<h2>Our Tours</h2>
<div className="underline"></div>
</div>
<div>
{tours.map((tour, index) => {
return <Tour key={tour.id} {...tours} />;
})}
</div>
</section>
);
};
export default Tours;
Tour Component
import React, { useState } from "react";
const Tour = ({ id, image, info, price, name }) => {
return (
<article className="single-tour">
<img src={image} alt={name} />
<footer>
<div className="tour-info">
<h4>{name}</h4>
<h4 className="tour-price">AUD{price}</h4>
</div>
<p>{info}</p>
<button className="delete-btn">Not Interested</button>
</footer>
</article>
);
};
export default Tour;
Try this code:
useEffect(async () => {
await fetchTours();
}, []);
I think your UI has not updated after the data arrived. You need to wait for your data is fetched.
Try to remove the setting of state in the function and move it to use effect. Have the API call only return the list instead of having it retrieving the list and setting the state.
const fetchTours = async () => {
const response = await fetch(url);
const tours = await response.json();
return tours;
};
useEffect(() => {
const fetchAndSetTourState = async () => {
const data = await fetchTours();
setTours(data);
setLoading(false);
}
fetchAndSetTourState();
}}, []);
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;
I am learning React as I am fetching data from Pokéapi to make a list component, card component, detail component and filter component. I am trying to make a filter so you can filter by pokémon type. Only the cards that also contain that type string should then render (Not there yet). So I am not sure if a) I should make a different call from API inside PokemonList depending on selected value or b) if I should compare the values and just change how the PokemonCard element is rendered inside PokemonList.js depending on the comparison. I managed to pass data from filter to the list component. I have then been trying to pass the type data from PokemonCard.js to the list component so that I can compare these two values but I find it hard to use callbacks to pass the type data from the card component, since I dont pass it through an event or something like that.
Which method should I use here to simplify the filtering? Make different API call or render PokemonCard element conditionally?
Is it a good idea to compare filter option to pokemon card's type in PokemonList.js? Then how can I pass that data from the card component since I don't pass it through click event?
Thankful for any ideas! I paste the code from list component that contains the cards, card component and filter component.
PokemonList component:
import { useState } from 'react';
import useSWR from 'swr';
import PokemonCard from './PokemonCard';
import PokemonFilter from './PokemonFilter';
import './PokemonList.css';
const PokemonList = () => {
const [index, setIndex] = useState(0);
const [type, setType] = useState('');
function selectedType(type) { // value from filter dropdown
setType(type)
console.log("handled")
console.log(type)
}
const url = `https://pokeapi.co/api/v2/pokemon?limit=9&offset=${index}`;
const fetcher = (...args) => fetch(...args).then((res) => res.json())
const { data: result, error } = useSWR(url, fetcher);
if (error) return <div>failed to load</div>
if (!result) return <div>loading...</div>
result.results.sort((a, b) => a.name < b.name ? -1 : 1);
return (
<section>
<PokemonFilter onSelectedType={selectedType} selectedPokemonType={type} />
<div className="pokemon-list">
<div className="pokemons">
{result.results.map((pokemon) => (
<PokemonCard key={pokemon.name} pokemon={pokemon} /> // callback needed??
))}
</div>
<div className="pagination">
<button
onClick={() => setIndex(index - 9)}
disabled={result.previous === null}
>
Previous
</button>
<button
onClick={() => setIndex(index + 9)}
disabled={result.next === null}
>
Next
</button>
</div>
</div>
</section>
)
}
export default PokemonList;
PokemonCard component:
import { Link } from "react-router-dom";
import useSWR from 'swr';
import './PokemonCard.css';
const PokemonCard = ({ pokemon }) => {
const { name } = pokemon;
const url = `https://pokeapi.co/api/v2/pokemon/${name}`;
const { data, error } = useSWR(url);
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
const { types, abilities } = data;
// types[0].type.name <---- value I want to pass to PokemonList.js
return (
<div className='pokemon-card'>
<div className='pokemon-card__content'>
<img
className='pokemon-card__image'
src={data.sprites.front_default}
alt={name}
/>
<div className='pokemon-card__info'>
<p className='pokemon-card__name'>Name: {name}</p>
<p className='pokemon-card__abilities'>Abilities: {abilities[0].ability.name}</p>
<p className='pokemon-card__categories'>Category: {types[0].type.name}</p>
</div>
</div>
<Link className='pokemon-card__link' to={{
pathname: `/${name}`,
state: data
}}>
View Details
</Link>
</div>
)
}
export default PokemonCard;
PokemonFilter component:
import './PokemonFilter.css';
import useSWR from 'swr';
const PokemonFilter = ({onSelectedType, selectedPokemonType}) => {
const url = `https://pokeapi.co/api/v2/type/`;
const fetcher = (...args) => fetch(...args).then((res) => res.json())
const { data: result, error } = useSWR(url, fetcher);
if (error) return <div>failed to load</div>
if (!result) return <div>loading...</div>
function filteredTypeHandler(e) {
console.log(e.target.value);
onSelectedType(e.target.value);
}
console.log(selectedPokemonType)
return(
<div className="pokemon-types__sidebar">
<h2>Filter Pokémon by type</h2>
<select
name="pokemon-type"
className="pokemon-types__filter"
onChange={filteredTypeHandler}
>
<option value="All">Filter By Type</option>
{result.results.map((type) => {
return (
<option key={type.name} value={type.name}> {type.name}</option>
)
})}
</select>
</div>
)
}
export default PokemonFilter;
Here is an example to improve, modify, ... I didn't test, it's just a visual example.
I don't know about useSWR sorry, I use axios in my example...
If you want to centralize all your API requests, you can create a useApi hook, on the internet you will find tutorials.
PokemonList.js
import React, { useState, useEffect } from 'react';
import axios from 'axios'; // or swr
import PokemonFilter from './PokemonFilter';
import PokemonCard from './PokemonCard';
export default function PokemonList() {
const [data, setData] = useState([]);
const [filter, setFilter] = useState('');
// Executed every first render
useEffect(() => {
getData();
}, []);
// Executed only when filter changes
useEffect(() => {
getDataByTypes(filter);
}, [filter]);
// Get data
const getData = async () => {
const uri = 'https://xxx';
try {
const response = await axios.get(uri);
setData(response.data...);
} catch (error) {
console.log(error);
}
};
// Get data by types
const getDataByTypes = async (filter) => {
const uri = `https://xxx/type/${filter}...`;
if (filter) {
try {
const response = await axios.get(uri);
setData(response.data...);
} catch (error) {
console.log(error);
}
}
};
return (
<div className="main">
<PokemonFilter filter={filter} setFilter={setFilter} />
<div className="container">
<div className="cards-container">
{data.map((d) => (
<PokemonCard key={d.name} data={d} />
))}
</div>
</div>
</div>
);
}
PokemonCard.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
export default function PokemonCard({ data }) {
const [pokemons, setPokemons] = useState();
useEffect(() => {
getPokemons(data);
}, [data]);
// Get Pokemons
const getPokemons = async (data) => {
const uri = `https://xxx/pokemon/${data.name}/`;
try {
const response = await axios.get(uri);
setPokemons(response.data...);
} catch (error) {
console.log(error);
}
};
return (
<div>
{pokemons && (
<div className="card">
<img src={pokemons.sprites.front_default} alt={pokemons.name} />
<p>{pokemons.name}</p>
<p>{pokemons.abilities[0].ability.name}</p>
<p>{pokemons.types[0].type.name}</p>
</div>
)}
</div>
);
}
PokemonFilter.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
export default function PokemonFilter({ filter, setFilter }) {
const [types, setTypes] = useState([]);
useEffect(() => {
getType();
}, []);
// Get Type
const getType = async () => {
const uri = 'https://xxx/type/';
try {
const response = await axios.get(uri);
setTypes(response.data.results....);
} catch (error) {
console.log(error);
}
};
const handleFilter = (e) => {
setFilter(e.target.value);
};
return (
<select onChange={handleFilter} value={filter}>
<option>Filter by type</option>
{types.map((type) => {
return (
<option key={type.name} value={type.name}>
{type.name}
</option>
);
})}
</select>
);
}
Is there any way by which I can show the latest post first in react
I was not able to find any way to solve this problem
import React from 'react'
import firebase from '../firebase'
import { useState, useEffect } from 'react';
import News from './News'
import logo from '../logo.svg';
import '../App.css'
export default function NewsProvider() {
const [news, setNews] = useState([]);
const [loading, setLoading] = useState(false);
const ref = firebase.firestore().collection("news");
function getNews() {
console.log("Loading news started");
setLoading(true);
ref.onSnapshot((querySnapshot) => {
const items = [];
querySnapshot.forEach((doc) => {
items.push(doc.data());
});
console.log("stopped");
setNews(items);
setLoading(false);
});
}
useEffect(() => {
getNews();
}, []);
if (loading) {
return (
<div>
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1>Loading</h1>
</header>
</div>
</div>
)
}
console.log(news);
return (
<div>
<News news = {news} />
</div>
)
}
Is there any way by which I can show the latest post first in react
In getNews function add new items to the beginning of an array with unshift
Be careful, unshift() overwrites the original array.
Here is an example:
const querySnapshot =["Banana","Orange","Apple","Mango","Lemon","Pineapple"];
const items = [];
querySnapshot.forEach((doc) => {
items.unshift(doc);
});
console.log(items);
just use .collection("news").orderBy("date","desc")
just make a new field in your database of dateTime
I can't seem to figure out why this is not working correctly. I have been looking it over for hours and I think I have it set up correctly but it keeps giving me the error. I am not sure if I have the state set incorrectly or not. When I console.log it its grabbing the sample data from the api and shows it in console.
import React, { useState, useEffect } from 'react'
import styled from 'styled-components'
import axios from 'axios'
import GuideData from './Guides/GuideData.js'
import GuideLoader from './Guides/GuideLoader.js'
const GuideRender= styled.div`
display:flex;
flex-direction:column;
justify-content:space-between;
border: 5px black;
`
const HomePage = () => {
const[guide, setGuide]=useState([]);
const apiLink ='https://how-to-guide-unit4-build.herokuapp.com/api/guides/'
useEffect(() => {
axios
.get(apiLink)
.then(response => setGuide(response))
.catch(err =>
console.log(err));
}, []);
console.log(guide)
if (!guide) return <GuideLoader />;
return (
<div>
<GuideRender>
{guide.map(item => (
<GuideData key={item} item={item} />
))}
</GuideRender>
<div>
<button>Create Article</button>
</div>
</div>
)
}
export default HomePage
Here you go, cleaned up your useEffect function a bit. The error was that you were setting just the response, and not response.data.
const HomePage = () => {
const [guide, setGuide] = useState([]);
const [loading, setLoading] = useState(true);
const apiLink = "https://how-to-guide-unit4-build.herokuapp.com/api/guides/";
useEffect(() => {
fetchData();
}, []);
const fetchData = async () => {
try {
const response = await axios.get(apiLink);
setGuide(response.data);
setLoading(false);
} catch (error) {
console.log(error);
}
};
if (loading) {
return "Loading...";
}
console.log(guide);
return (
<div>
<GuideRender>
{guide.map(item => (
<GuideData key={item} item={item} />
))}
</GuideRender>
<div>
<button>Create Article</button>
</div>
</div>
);
};
Your code seems fine. You can use optional chaining to avoid components breaking while API intergration. Working sandbox
I have fetched some information an API and now I am trying to show the information fetched from it. The information which I have fetched includes books_authors , books_id's , price and the dataset is quite large and I am unable to display this information from my following approach...can someone help me with it... I am new to react
This is what I have tried so far:
import React from "react";
import Head from './head';
function App(){
let s;
const proxy = 'http://cors-anywhere.herokuapp.com/';
const api = `${proxy}http://starlord.hackerearth.com/books`;
fetch(api)
.then(response =>{
return response.json();
})
.then(data =>{
console.log(data);
data.forEach((index) => {
s=index;
<Head s/>
});
});
return(
<Head />
);
}
export default App;
//the head component
import React from "react";
function Head(props){
return(
<div className="app">
<div className="heading">
<h1>BOOK_CAVE</h1>
<div className="heading_description">So many books...so
little time...</div>
</div>
<div className="author">{props.authors}</div>
<div className="id">{props.bookID}</div>
<div className="price">{props.price}</div>
</div>
);
}
export default Head;
You can do this using Hooks, useState to store data and useEffect to call API,
import React, {useState,useEffect} from "react";
import Head from './head';
function App(){
const [data, setData] = useState([])
useEffect(() => {
const proxy = 'http://cors-anywhere.herokuapp.com/';
const api = `${proxy}http://starlord.hackerearth.com/books`;
fetch(api).then(response => {
setData(response.json())
})
},[])
return(
<div>
{data.length>0 && data.map(book => <Head book={book} />)
</div>
);
}
And you Head component should be,
function Head(props){
return(
<div className="app">
<div className="heading">
<h1>BOOK_CAVE</h1>
<div className="heading_description">So many books...so
little time...</div>
</div>
<div className="author">{props.book.authors}</div>
<div className="id">{props.book.bookID}</div>
<div className="price">{props.book.price}</div>
</div>
);
}
The books array you fetch from the API should be stored in a state and you should render the app according to that state. The data fetching should happen when the component mounted, so you make the call on componentDidMount lifecycle method, and update the state when the data finished fetching. Also, the Head component recieves three props, but you pass only one.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
books: [],
fetching: true,
}
componentDidMount() {
const proxy = 'http://cors-anywhere.herokuapp.com/';
const api = `${proxy}http://starlord.hackerearth.com/books`;
fetch(api)
.then(response => response.json() )
.then(data => this.setState({books: data, fetching: false,}) );
}
render() {
if (this.state.fetching) {
return <div>Loading...</div>
}
const headArray = this.state.books.map(book => (
<Head
authors={book.authors}
bookID={book.bookID}
price={book.price}
/>
));
return(
<div>
{headArray}
</div>
);
}
}
You need to:
Enclose the fetch n a lifecycle method or a useEffect hook
Put the API's response in a state (which will cause a re-render)
Iterate over the state in the return statement, using map, not forEach
Example using hooks:
function App(){
const [apiData, setApiData] = useState([])
const [isLoading, setIsLoading] = useState(true)
useEffect(
() => {
const proxy = 'http://cors-anywhere.herokuapp.com/';
const api = `${proxy}http://starlord.hackerearth.com/books`;
fetch(api).then(response => {
setApiData(response.json())
setIsLoading(false)
})
},
[]
)
const authors = data.map((index) => index.authors).flat()
return(
<div>
{authors.map((author) => <Head author{author} />)
</div>
);
}