Display data from jsonplaceholder api using react hooks - javascript

I have simple rest api, I am trying to display users from jsonplaceholder fake api
Here is my function component
import React, {useState, useEffect} from "react";
import axios from 'axios';
export default function TableList() {
const [data, setData] = useState({ hits: [] });
useEffect(() => {
const fetchData = async () => {
const result = await axios(
'https://jsonplaceholder.typicode.com/users',
);
setData(result.data);
console.log(result.data);
};
fetchData();
}, []);
return (
<div>
<ul>
{data.hits.map(item => (
<li key={item.id}>
<h1>{item.name}</h1>
</li>
))}
</ul>
</div>
);
}
Unfortunately, I am getting the following error:
TableList.js:22 Uncaught TypeError: Cannot read property 'map' of undefined
What is wrong with my code?

You're setting the data incorrectly and you should null check data.hits. Here's a working example
function TableList() {
const [users, setUsers] = useState({ hits: [] });
useEffect(() => {
const fetchData = async () => {
const { data } = await axios(
"https://jsonplaceholder.typicode.com/users"
);
setUsers({ hits: data });
};
fetchData();
}, [setUsers]);
return (
<div>
<ul>
{users.hits &&
users.hits.map(item => (
<li key={item.id}>
<span>{item.name}</span>
</li>
))}
</ul>
</div>
);
}
https://codesandbox.io/s/affectionate-lehmann-17qhw

"hits" is necesary?.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
export default function MiJSON(){
const [users, setUsers] = useState([]);
const urlJson= 'https://jsonplaceholder.typicode.com/users';
useEffect(()=>{
const fetchData = async ()=>{
const users_data = await axios(urlJson);
setUsers(users_data);
};
fetchData();
},[setUsers])
console.log(users)
return (
<div>
<h1>USERS</h1>
<ul>
{(users.length !== 0)
?
users.data.map(item => (
<li key={item.id}>
<span>{item.name}</span>
</li>
))
: <h1>Sorry info not found</h1>
}
</ul>
</div>
)
}

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 to solve the problem with 'map' function on React?

I'm doing project on React.js. I'm mapping the array and the error saying that the array is undefine even if it exists
<ul>
{details.extendedIngredients.map(ingredient => (
<li id={ingredient.id}>{ingredient.original}</li>
))}
</ul>
Full code:
import { useEffect, useState } from "react";
import styled from "styled-components";
import { useParams } from "react-router-dom";
function Recipe() {
let params = useParams();
const [details, setDetails] = useState({});
const [activeTab, setActiveTab] = useState("instructions");
const fetchDetails = async () => {
const data = await fetch(
`https://api.spoonacular.com/recipes/${params.name}/information?apiKey=${process.env.REACT_APP_API_KEY}`
);
const detailData = await data.json();
setDetails(detailData);
};
useEffect(() => {
fetchDetails();
}, [params.name]);
console.log(details.extendedIngredients);
return (
<DetailWrapper>
<div>
<h2>{details.title}</h2>
<img src={details.image} alt="" />
</div>
<Info>
<Button
className={activeTab === "instructions" ? "active" : ""}
onClick={() => setActiveTab("instructions")}
>
Instructions
</Button>
<Button
className={activeTab === "ingredients" ? "active" : ""}
onClick={() => setActiveTab("ingredients")}
>
Ingredients
</Button>
<div>
<h3 dangerouslySetInnerHTML={{ __html: details.summary }}></h3>
<h3 dangerouslySetInnerHTML={{ __html: details.instructions }}></h3>
</div>
<ul>
{details.extendedIngredients.map(ingredient => (
<li id={ingredient.id}>{ingredient.original}</li>
))}
</ul>
</Info>
</DetailWrapper>
)}
export default Recipe;
As setDetails supposed to save the details received from your API in an array, I guess that it must be initialised as an empty array
const [details, setDetails] = useState({});
As it will be an empty array, there will be no render when the component will be mounted from react.
Should be:
const [details, setDetails] = useState({});
edit this three parts:
first Part:
useEffect(() => {
fetchDetails().then(res=>
{setDetails(res.data); console.log(res)}
);
}, []);
second Part:
<ul>
{details?.extendedIngredients?.map(ingredient => (
<li id={ingredient.id}>{ingredient.original}</li>
))}
</ul>
third Part:
const fetchDetails = async (params) => {
const data = await fetch(
`https://api.spoonacular.com/recipes/${params.name}/information?
apiKey=${process.env.REACT_APP_API_KEY}`
return data;
);

React JS API item.map

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

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>

React with Axios can't map array to list

I'm trying to map all the names in this object but I can't figure out how to access the array. How can i map an object that has multiple array values? Sorry if my question doesn't make sense.
import React, { useEffect, useState } from "react";
import axios from "axios";
const ApiTest = (props) => {
const [data, setData] = useState({ name: [] });
useEffect(() => {
const fetchData = async () => {
const result = await axios("https://jsonplaceholder.typicode.com/users");
setData(result.data);
console.log(typeof result.data);
console.log(result.data);
};
fetchData();
}, []);
return (
<ul>
{data.map((item) => (
<li key={item.id}>
<a>{item.name}</a>
</li>
))}
</ul>
);
};
export default ApiTest;
This will correct the issue
const [data, setData] = useState([]);

Categories