React with Axios can't map array to list - javascript

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

Related

TypeError: Cannot destructure property 'company' of 'jobs[value]' as it is undefined

I am using useEffect and useState hooks to fetch data and destructure it. But I'm getting this error every time.
Here is the code.
import React, { useState, useEffect } from 'react';
import { FaAngleDoubleRight } from 'react-icons/fa';
import Jobs from './Jobs';
// ATTENTION!!!!!!!!!!
// I SWITCHED TO PERMANENT DOMAIN
const url = 'https://course-api.com/react-tabs-project';
function App() {
const [loading, setLoading] = useState(true);
const [jobs, setJobs] = useState([]);
const [value, setValue] = useState(0);
const fetchJobs = async () => {
const response = await fetch(url);
const newJobs = await response.json();
setJobs(newJobs);
setLoading(false);
// console.log(newJobs);
};
useEffect(() => {
fetchJobs();
}, []);
const{company, dates, duties, title}=jobs[value];
console.log(jobs[value]);
// const { company, dates, duties, title } = jobs[value];
return (
<section className='section '>
<div className='title'>
<h2>experience</h2>
<div className='underline'></div>
</div>
{/* <Jobs jobs={jobs} /> */}
</section>
);
}
export default App;
Error image
If I comment out the destructuring, I get the value 6 times. The First 2 times it is undefined.
browser console
You are destructuring properties from the object when still the data is not fetched and the array length is 0
import React, { useState, useEffect } from "react";
import { FaAngleDoubleRight } from "react-icons/fa";
import Jobs from "./Jobs";
// ATTENTION!!!!!!!!!!
// I SWITCHED TO PERMANENT DOMAIN
const url = "https://course-api.com/react-tabs-project";
function App() {
const [loading, setLoading] = useState(true);
const [jobs, setJobs] = useState([]);
const [value, setValue] = useState(0);
const [currentJob, setCurrentJob] = useState();
const fetchJobs = async () => {
const response = await fetch(url);
const newJobs = await response.json();
setJobs(newJobs);
setLoading(false);
if (newJobs.length > 0) setCurrentJob(newJobs[value]);
// console.log(newJobs);
};
useEffect(() => {
fetchJobs();
}, []);
// const{company, dates, duties, title}=jobs[value];
// console.log(jobs[value]);
if (loading) return <h2>Loading...</h2>;
return (
<section className="section ">
<div className="title">
<h2>experience</h2>
<div className="underline"></div>
</div>
{/* <Jobs jobs={jobs} /> */}
</section>
);
}
export default App;
I have added another state variable currentJob which will assume the job item based on value variable when successfully the fetch is completed, although I would suggest to use the jobs array directly based on your component requirements.

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.js: why search filter doesn't work?

I am trying to make work search input. I'm filtering through fetched data in useEffect in Hooks/useCountries component, listening to input in App.js and passing props for handleChange in Searchbar component. Something is missing, I can't figure out what. Here is the link of codesandbox and Hooks/useCountries component
import React, { useState, useEffect } from "react";
export default function useCountries(search) {
const [data, setData] = useState([]);
const [error, setError] = useState(null);
const fetchData = () => {
fetch("https://restcountries.eu/rest/v2/all")
.then((res) => res.json())
.then((result) => setData(result))
.catch((err) => console.log("error"));
};
useEffect(() => {
const searchResult =
data &&
data
.filter((item) => item.name.toLowerCase().includes(search))
.map((element) => <div>{element.name}</div>);
}, []);
useEffect(() => {
fetchData();
}, []);
return [data, error];
}
App.js
import React, { useState } from "react";
import SearchBar from "./components/SearchBar";
import useCountries from "./Hooks/useCountries";
import MainTable from "./components/MainTable";
import "./App.scss";
export default function App() {
const [search, setSearch] = useState("");
const [data, error] = useCountries(search);
const handleChange = (e) => {
setSearch(e.target.value);
};
return (
<div className="App">
<SearchBar handleChange={handleChange} search={search} />
<MainTable countries={data} />
</div>
);
}
SearchBar component
import React, { useState } from "react";
import "./SearchBar.scss";
export default function Searchbar({ handleChange, search }) {
return (
<div className="SearchBar">
<input
className="input"
type="text"
placeholder="search country ..."
value={search}
onChange={handleChange}
/>
</div>
);
}
So in your useCountries hook, you need to update the useEffect to trigger whenever search is changed. Otherwise, it runs when the hook is first loaded, but then never again. I'm also not exactly sure what your logic is attempting to accomplish in your current useEffect. I've posted a possible update to it that also changes your search to regex to account for the possibility that the user may not be typing in lower case. Let me know if this doesn't work for your use case and I can adapt it.
import React, { useState, useEffect } from "react";
export default function useCountries(search) {
const [data, setData] = useState([]);
const [error, setError] = useState(null);
const [searchResults, setSearchResults] = useState(null);
const fetchData = () => {
fetch("https://restcountries.eu/rest/v2/all")
.then((res) => res.json())
.then((result) => setData(result))
.catch((err) => console.log("error"));
};
useEffect(() => {
if (search) {
const searchCriteria = new RegExp(search, "i");
setSearchResults(
data
.filter((item) => searchCriteria.test(item.name))
.map((element) => <div>{element.name}</div>)
);
} else {
setSearchResults(null);
}
}, [search]);
useEffect(() => {
fetchData();
}, []);
return [data, error, searchResults];
}
And in App.js add:
const [data, error, searchResults] = useCountries(search);
Here is the fork off of your sandbox where this works:
CodeSandbox

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