undefined is not an object axios - javascript

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>

Related

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

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

Failed to compile: Module not found: Can't resolve in ReactJS

I was about rounding up this activity and I started getting this error:
Module not found: Can't resolve './components/Post' in ./src/pages/index.js
I have tried all I could but was not able to solve this problem. Below is the list of my codes:
index.js
import React, { useState, useEffect } from 'react';
import Posts from './components/Pagination';
import Pagination from './components/Post';
import axios from 'axios';
const Home = () => {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(false);
const [currentPage, setCurrentPage] = useState(1);
const [postsPerPage] = useState(10);
useEffect(() => {
const fetchPosts = async () => {
setLoading(true);
const res = await axios.get('https://jsonplaceholder.typicode.com/posts');
setPosts(res.data);
setLoading(false);
};
fetchPosts();
}, []);
// Get current posts
const indexOfLastPost = currentPage * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
const currentPosts = posts.slice(indexOfFirstPost, indexOfLastPost);
// Change page
const paginate = pageNumber => setCurrentPage(pageNumber);
return (
<div
style={{
display: 'flex',
height: '90vh'
}}
>
<img src={require('../images/top_img.jpg')} alt='logo' height='500px' width='100%'/>
<div className='container mt-5'>
<h1 className='text-primary mb-3'>LATEST NEWS</h1>
<Posts posts={currentPosts} loading={loading} />
<Pagination
postsPerPage={postsPerPage}
totalPosts={posts.length}
paginate={paginate}
/>
</div>
</div>
);
};
export default Home;
Post.js
import React from 'react';
const Posts = ({ posts, loading }) => {
if (loading) {
return <h2>Loading...</h2>;
}
return (
<ul className='list-group mb-4'>
{posts.map(post => (
<li key={post.id} className='list-group-item'>
{post.title}
</li>
))}
</ul>
);
};
export default Posts;
Pagination.js
import React from 'react';
const Posts = ({ posts, loading }) => {
if (loading) {
return <h2>Loading...</h2>;
}
return (
<ul className='list-group mb-4'>
{posts.map(post => (
<li key={post.id} className='list-group-item'>
{post.title}
</li>
))}
</ul>
);
};
export default Posts;
Below is the structure of my code:
I believe your object names are swapped.
Isn't there an error of relative path?
import Posts from '../components/Pagination';
import Pagination from './components/Post';
both imports are in the same file and both files are in the same folder, but one has ../ and other ./
First, you I would make the named imports match the file structure:
import Post from "./components/Post"
import Pagination from "./components/Pagination"
Also, your default exports are messing things up as well. You will want to export Pagination and then in ./Post you want to export Post.
Lastly, your paths were messed up. The "components" folder is on the same level as index.js. Thus, you can access it through "./components"

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([]);

Display data from jsonplaceholder api using react hooks

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>
)
}

Categories