React JS API item.map - javascript

import React, { useState, useEffect, } from "react";
function ProductDetail({match}) {
useEffect(() => {
fetchItem();
// console.log(match)
}, );
const fetchItem = async () => {
const fetchItem = await fetch(`https://fortnite-api.theapinetwork.com/item/get?id={{itemid}}`);
const item = await fetchItem.json();
console.log(item);
}
return (
<div className="containter productsDetails">
<h1>Product Detail</h1>
</div>
);
}
export default ProductDetail;
enter image description here
import React, { useState, useEffect } from "react";
import {Link} from "react-router-dom";
function Products() {
const [data, setData] = useState([]);
const apiGet = () => {
fetch(`https://fortnite-api.theapinetwork.com/items/popular`)
.then((response) => response.json())
.then((json) => {
console.log(json);
setData(json);
});
};
useEffect(() => {
apiGet();
},[])
return (
<div>
<div>
<ul>
{data.map(item =>
<li key={item.id}>
<Link to={`/products/${item.id}`}>{item.item}</Link>
</li>
)}
</ul>
</div>
</div>
);
}
export default Products;
I have tried every way I can find online.
I am unable to map into the entries object of this API. I would like to map to the 3 array objects.
So that I can {match} using an ID when I click one of them.
The routing is working. But I can not display any of the data on the screen. In Console it is displaying.
He is the API fortnite-api.theapinetwork.com/items/popular

You're trying to use map function on object. map only works for arrays.
Here's the link to sandbox how it should be

Related

How do I print the data from axios result?

I am getting the response and storing that into the array but I am unable to destructure the data from that array,How do i log title of every product inside the div ?
import React, { useEffect, useState } from "react";
import axios from "axios";
const ProductsAPI = () => {
const [item, setItem] = useState([]);
useEffect(() => {
axios
.get("https://fakestoreapi.com/products")
.then((res) => setItem(res.data));
}, []);
return <div></div>;
};
export default ProductsAPI;
You can map over the state value inside your render
<div>
<ul>
{item.map((item,index) =><li key={index}>
{item.title}
</li>) }
</ul>
</div>
You need to loop through your res.data by mapping inside of your render().
useEffect(() => {
axios.get(`https://fakestoreapi.com/products`)
.then(res => {
const yourSavedData = res.data;
this.setState({yourSavedData });
})
}
render() {
return (
<div>
{
this.state.yourSavedData
.map(someName => // <-- Your Callback
<div data-something={yourSavedData.whatever_key}>{yourSavedData.another_key}</div><br />
)
}
</div>
)
}

How do I target each image seperately, and fetch API data from them, instead of collect it all at once

I've created an app that connects to an API that retrieves dog images. On page load, 12 images are displayed, along with json text, that provides information about the breeds; height of the dog etc.
My final step would be somehow connecting the a button (which already exists) to each individual image, then retrieving data for that one specific dog/image after clicking it, instead of the API fetching all of the data at once on initial page load.
App.js
import './App.css';
import './Dog.js';
import './index.css';
import FetchAPI from './FetchAPI';
function DogApp() {
return (
<div className="dogApp">
<FetchAPI />
</div>
);
}
export default DogApp;
FetchAPI.js
import React, { useState, useEffect } from 'react'
const FetchAPI = () => {
const [data, setData] = useState([]);
const apiGet = () => {
const API_KEY = "";
fetch(`https://api.thedogapi.com/v1/images/search?limit=12&page=10&order=Desc?API_KEY=${API_KEY}`)
.then((response) => response.json())
.then((json) => {
console.log(json);
//setData([...data,json]); if json is single object
setData([...data, ...json]); // if json is array of one object then use this line
});
};
useEffect(() => { //call data when pagee refreshes/initially loads
apiGet();
}, []);
return (
<div>
{data.map((item) => (
<div class="dog">
<img src={item.url}></img>
<button onClick={item.breeds}>Fetch API</button>
</div>
))}
{data.map((item) => (
<p>{JSON.stringify(item.breeds)}</p>
))}
{/*<pre>{JSON.stringify(data, null, 2)}</pre> */}
<br />
</div>
)
}
export default FetchAPI;
Make an other function which will fetch new (single) image and change it to the state as I have made function named apiGetSingle which changes the data on specific index. And if you have made the route as I have mentioned in apiGetSingle which will return single new image then it will work fine otherwise made backend route for that too.
import React, { useState, useEffect } from 'react'
const FetchAPI = () => {
const [data, setData] = useState([]);
const apiGet = () => {
const API_KEY = "";
fetch(`https://api.thedogapi.com/v1/images/search?limit=12&page=10&order=Desc?API_KEY=${API_KEY}`)
.then((response) => response.json())
.then((json) => {
console.log(json);
//setData([...data,json]); if json is single object
setData([...data, ...json]); // if json is array of one object then use this line
});
};
const apiGetSingle = (index) => {
const API_KEY = "";
fetch(`https://api.thedogapi.com/v1/images/search?API_KEY=${API_KEY}`)
.then((response) => response.json())
.then((json) => {
console.log(json);
let d=[...data];
d[index]=json; // if json is single object.
d[index]=json[0] // if json returns array
setData(d);
};
useEffect(() => {
}, []);
return (
<div>
{data.map((item,index) => (
<div class="dog">
<img src={item.url}></img>
<button onClick={()=>apiGetSingle(index)}>Fetch API</button>
</div>
))}
{data.map((item) => (
<p>{JSON.stringify(item.breeds)}</p>
))}
<button onClick={apiGet}>Fetch API</button>
{/*<pre>{JSON.stringify(data, null, 2)}</pre> */}
<br />
</div>
)
}
export default FetchAPI;

undefined is not an object axios

I'm getting this error when i try to use GET method in AXIOS. At the bottom I put a code snippet without style. Wants to grab data from the API using AXIOS. I'm new and don't quite know how to do this correctly.
undefined is not an object (evaluating 'data.map')
code:
import React, {useState, useEffect} from 'react';
import axios from 'axios';
const HomeScreen = ({navigation}) => {
const [categoryIndex, setCategoryIndex, data, setData] = useState([])
useEffect(() => {
const fetchData = async () => {
const result = await axios(
'https://hn.algolia.com/api/v1/search?query=redux',
);
setData(result.data);
};
fetchData();
}, []);
return (
<SafeAreaView
<ul>
{data.map(item => (
<li key={item.objectID}>
<a href={item.url}>{item.title}</a>
</li>
))}
</ul>
</SafeAreaView>
);
};
export default HomeScreen;
Hi, your data is not like you expected. There is also "hits" variable that exists, I think you want to show that data.
In the first render, it's trying to map your data but data was not filled when trying to map it.
Also, you should be re-examined "useState" usage.
And you need to check if data exist before the map it (data?.hits).
And you forgot to close the SafeAreaViewtag.
https://reactjs.org/docs/hooks-state.html
https://codesandbox.io/s/ancient-fast-pdqhy?file=/src/TestApp.jsx
If you paste this it will work correctly:
import React, { useState, useEffect } from "react";
import axios from "axios";
const HomeScreen = ({ navigation }) => {
const [data, setData] = useState([]);
const [categoryIndex, setCategoryIndex] = useState([]);
useEffect(() => {
const fetchData = async () => {
const result = await axios(
"https://hn.algolia.com/api/v1/search?query=redux"
);
console.log(result);
setData(result.data);
};
fetchData();
}, []);
return (
<SafeAreaView>
<ul>
{data?.hits &&
data.hits.map((item) => (
<li key={item.objectID}>
<a href={item.url}>{item.title}</a>
</li>
))}
</ul>
</SafeAreaView>
);
};
export default HomeScreen;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Making List of Map from Other Component Show in HTML

I tried to make new component for list film. But it seems error in page Home.
Here my code in component list map:
import './Home.css';
import './ListFilm';
import ListFilm from './ListFilm';
function Home() {
return (
<div className="Home">
<h2>The List of Films</h2>
<div className="list film">
<ListFilm/>
</div>
</div>
);
}
export default Home;
Here is component file named ListFilm.js :
import {useState, useEffect} from 'react';
function ListFilm() {
const [post, setPost] = useState({});
useEffect(() => {
const fetchData = async () => {
const response = await fetch(
"https://api.themoviedb.org/3/movie/now_playing?api_key=9e0de5499870264659308848dbad6b2a"
);
const data = await response.json();
setPost(data);
console.log(response)
console.log(data);
};
fetchData();
}, []);
return (
<>
{post.results && post.results.map((item, index) => (
<div key={index}>
<h3>{item.original_title}</h3>
<img src={item.backdrop_path} alt="poster"/>
<p>Tanggal Rilis: {item.release_date}</p>
</div>
))}
</>
);
}
export default ListFilm;
The goal is making data and image in listfilm.js showing in page Home.js. The error code in console log said that index.js:1 The above error occurred in the component: Please help me. Thanks

Reducer/Context Api

So I have a Context created with reducer. In reducer I have some logic, that in theory should work. I have Show Component that is iterating the data from data.js and has a button.I also have a windows Component that is iterating the data. Anyway the problem is that when I click on button in Show Component it should remove the item/id of data.js in Windows Component and in Show Component, but when I click on it nothing happens. I would be very grateful if someone could help me. Kind regards
App.js
const App =()=>{
const[isShowlOpen, setIsShowOpen]=React.useState(false)
const Show = useRef(null)
function openShow(){
setIsShowOpen(true)
}
function closeShowl(){
setIsShowOpen(false)
}
const handleShow =(e)=>{
if(show.current&& !showl.current.contains(e.target)){
closeShow()
}
}
useEffect(()=>{
document.addEventListener('click',handleShow)
return () =>{
document.removeEventListener('click', handleShow)
}
},[])
return (
<div>
<div ref={show}>
<img className='taskbar__iconsRight' onClick={() =>
setIsShowOpen(!isShowOpen)}
src="https://winaero.com/blog/wp-content/uploads/2017/07/Control-
-icon.png"/>
{isShowOpen ? <Show closeShow={closeShow} />: null}
</div>
)
}
```Context```
import React, { useState, useContext, useReducer, useEffect } from 'react'
import {windowsIcons} from './data'
import reducer from './reducer'
const AppContext = React.createContext()
const initialState = {
icons: windowsIcons
}
const AppProvider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState)
const remove = (id) => {
dispatch({ type: 'REMOVE', payload: id })
}
return (
<AppContext.Provider
value={{
...state,
remove,
}}
>
{children}
</AppContext.Provider>
)
}
export const useGlobalContext = () => {
return useContext(AppContext)
}
export { AppContext, AppProvider }
reducer.js
const reducer = (state, action) => {
if (action.type === 'REMOVE') {
return {
...state,
icons: state.icons.filter((windowsIcons) => windowsIcons.id !== action.payload),
}
}
}
export default reducer
``data.js```
export const windowsIcons =[
{
id:15,
url:"something/",
name:"yes",
img:"/images/icons/crud.png",
},
{
id:16,
url:"something/",
name:"nine",
img:"/images/icons/stermm.png",
},
{
id:17,
url:"domething/",
name:"ten",
img:"/images/icons/ll.png",
},
{
id:18,
url:"whatever",
name:"twenty",
img:"/images/icons/icons848.png",
},
{
id:19,
url:"hello",
name:"yeaa",
img:"/images/icons/icons8-96.png",
},
]
``` Show Component```
import React from 'react'
import { useGlobalContext } from '../../context'
import WindowsIcons from '../../WindowsIcons/WindowsIcons'
const Show = () => {
const { remove, } = useGlobalContext()
return (
<div className='control'>
{windowsIcons.map((unin)=>{
const { name, img, id} = unin
return (
<li className='control' key ={id}>
<div className='img__text'>
<img className='control__Img' src={img} />
<h4 className='control__name'>{name}</h4>
</div>
<button className='unin__button' onClick={() => remove(id)} >remove</button>
</li> )
</div>
)
}
export default Show
import React from 'react'
import {windowsIcons} from "../data"
import './WindowsIcons.css'
const WindowsIcons = ({id, url, img, name}) => {
return (
<>
{windowsIcons.map((icons)=>{
const {id, name , img ,url} =icons
return(
<div className='windows__icon' >
<li className='windows__list' key={id}>
<a href={url}>
<img className='windows__image' src={img}/>
<h4 className='windows__text'>{name}</h4>
</a>
</li>
</div>
)
})}
</>
)
}
Issue
In the reducer you are setting the initial state to your data list.
This is all correct.
However, then in your Show component you are directly importing windowsIcons and looping over it to render. So you are no longer looping over the state the reducer is handling. If the state changes, you won't see it.
Solution
In your Show component instead loop over the state that you have in the reducer:
const { remove, icons } = useGlobalContext()
{icons.map((unin) => {
// Render stuff
}
Now if you click remove it will modify the internal state and the icons variable will get updated.
Codesandbox working example

Categories