I want to fetch data from given API(link is censored in code example), but cant manage to to display product.name from my Api fetch.
import { useState, useEffect } from "react";
import axios from "axios";
function DataFetching() {
const [posts, setPosts] = useState([]);
useEffect(() => {
axios
.get("https://CENSORED/")
.then((res) => {
console.log(res);
setPosts(res.data);
})
.catch((err) => {
console.log(err);
});
}, []);
return (
<div>
<div>
{posts.map((post) => (
<h1>{post.product.name}</h1>
))}
</div>
</div>
);
}
Errors
The error is because the posts array is empty initially you need to check first if the array has some data then perform a map
setPosts(res.data.product)
{posts?.map((post) => (
<h1>{post.name}</h1>
))}
or you can use conditional like this
{ posts.length > 0
? posts.map((post) => (
<h1>{post.name}</h1>
))
: <Your custom message/>
}
res.data is indicated to be an object in the console.log. the map method will only work on arrays. If you were expecting an array, make sure you aren't hitting the "detail" endpoint, which would return specific information about a post.
Related
I am quite new in learning React and now I am trying to implement some dynamic filters on a locat data set and I am stuck at displaying data from my local file.
Data entries look like this:
I was trying to use the fetch() API but for some reason the data is not displayed on the page. Most probably I am not reffering correct to the right attributes.
`
import data from '../file2.json'
import React, { useEffect, useState } from "react";
const Planner = () => {
const [user, setUser] = useState([]);
const fetchData = () => {
return fetch(data)
.then((response) => response.json())
.then((data) => setUser(data));
}
useEffect(() => {
fetchData();
},[])
return (<main>
<h1>Restaurant List</h1>
<ul>
{user && user.length > 0 && user.map((userObj, index) => (
<li key={userObj.restaurant.R.res_id}>{userObj.name}</li>
))}
</ul>
</main>
)
};
export default Planner;`
I have a simple fetch request that runs only on the first render. When I update the state with the data and try to map through it nothing is shown. For reference the data I am given back is just one entry. Using .map it should for each entry ( which is 1) display a bullet but nothing is shown.
{quote: "I'm the new Moses"}
import logo from './logo.svg';
import {useState,useEffect} from 'react';
import './App.css';
function App() {
const [users, setUsers] = useState([])
const fetchData = () => {
fetch("https://api.kanye.rest/")
.then(response => {
return response.json()
})
.then(data => {
console.log(data)
setUsers(data)
})
}
useEffect(() => {
fetchData()
}, [])
return (
<div className="App">
<body className='App'>
<div>
{users.length > 0 && (
<ul>
{users.map(user => (
<li>{user.quote}</li>
))}
</ul>
)}
</div>
</body>
</div>
);
}
export default App;
The response value {quote: "I'm the new Moses"} is an object, not an array. It can't be mapped.
Place the response value in an array when saving.
const fetchData = () => {
fetch("https://api.kanye.rest/")
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
setUsers([data]);
});
};
The result you got isn't an array, it's an object. It can't be mapped. However, you can achieve your expected behaviour in many ways. One of them is just put data into an array while setting user.
setUsers([data])
I built a react code using useEffect()and Axios to get a json from an URL, however I'm getting an empty array, probably because it is not async function. Here is my code:
import axios from "axios";
import { useEffect, useState } from "react";
export function UseVacation (){
const[vacations, setVacations] = useState([]);
useEffect(() =>{
axios.get('APILINK').then( async (res) =>{
setVacations(res.data);
console.log("vactest: "+ JSON.stringify(vacations))
}).catch((err)=>{
alert("Error extracting the data from API: "+err);
})
}, [])
return (
<div>
{vacations.map( (vac) => {
<h1>{vac._id}</h1>
})}
</div>
)
}
Any idea on this?
Why dont you console res.data instead of vacations and see what it has ? Also check the network tab, and see what actual request has in the response
I've changed my return and it fixed issue. Why? I don't know, but is working:
return (
<div>
{vacations.map( (vac) => {
return(
<h1>{vac?._id}</h1>
)
})}
</div>
)
Have you tried the following?
return (
<div>
{vacations && vacations.map( (vac) => {
<h1>{vac._id}</h1>
})}
</div>
)
I have good suggestion for you:
const[vacations, setVacations] = useState([]);
useEffect(() => {
const getApi = async () => {
try {
const res = await axios.get('APILINK')
setVacations(res.data);
} catch(error) {
console.log(error)
}
}
getApi()
}, [])
console.log("vactest: "+ vacations)
I cannot explain but if you set state in useEffect and direct log state in useEffect, it only log previous state
I'm making a simple API call from a react component to my Mongo database, which returns a list of items.
Inside useEffect, I'm making a GET request to return an arrays of reviews. When I log the resulting to the data, I'm seeing the correct information:
useEffect(() => {
axios.get('http://localhost:3000/all-reviews')
.then((allReviews) => {
console.log(allReviews)
})
})
However, when I try to set state inside the useEffect method, my program breaks. I know that setState is async, so how do I configure it so it works inside useEffect?
Here's the entire component used to control API calls:
App.jsx
import React, {useState, useEffect} from 'react'
import axios from 'axios'
const App = () => {
const [reviews, setReviews] = useState([])
useEffect(() => {
axios.get('http://localhost:3000/all-reviews')
.then((allReviews) => {
setReviews(allReviews)
})
})
return (
<>
<h1>React development has begun!</h1>
{
reviews.map((item, index) => {
<h1>item.title</h1>
})
}
</>
)
}
export default App
Not that relevant, but here's the route this component invokes:
server.get('/all-reviews', (req,res) => {
Review.find()
.then((result) => {
res.send(result)
})
.catch(err => {
console.log(err)
})
})
I think firstly, your useEffect doesn't have a depedency, which mean it will run every time, it needs an empty array at least, like the one below.
useEffect(() => {
},[])
And when you are expecting a JSON data in React, you have to check if the data is available first before populating it, if not react will freak out.
You could do this.
return (
<>
<h1>React development has begun!</h1>
{
reviews?.map((item, index) => {
<h1>item.title</h1>
})
}
</>
)
}
or this
return (
<>
<h1>React development has begun!</h1>
{
reviews && (reviews.map((item, index) => {
<h1>item.title</h1>
}))
}
</>
)
}
and thirdly you are not returning anything in your dom.
it should be this way.
reviews && (reviews.map((item, index) =>
<h1>item.title</h1>
))
or if you wanna do it your way, you could just do this.
reviews && (reviews.map((item, index) => {
return (
<h1>item.title</h1>
)
}))
I am new to react hooks. I am trying to cast API response into an array using react useState hook. It's giving me empty with the below approach
const [post, setPostArray] = useState([]);
useEffect(() => {
const postparams = { userList: result };
axios
.get(environment._urlPosts, { headers, params: postparams })
.then(posts => {
// storing response data in array
setPostArray(posts.data.post);
console.log(post);
})
.catch(err => {});
}, []);
Then I used the below approach and I was able to see data is printing in the console log
axios.get(environment._urlPosts, { headers, params: postparams }).then(posts => {
// storing response data in array
for (let obj of posts.data.post) {
post.push(obj)
}
setPostArray(post)
console.log(post)
But when I try to iterate this post array in my JSX, it's giving me empty array.
</div>
{/* array length */}
{post.length}
{post.map(post =>
<div className="card">
<Post username={post.username} fullname={post.fullname} postedTime={post.postedTime} postContent='Hi' tweeterLike={post.tweeterLike} />
</div>
)}
Can you please help me to resolve this?
Here is a minimal Example of what you are trying to achieve.
This is the working code:
import React, {useEffect, useState} from "react";
import "./styles.css";
export default function App() {
const [post, setPostArray] = useState([])
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => {
console.log(json);
setPostArray([json]);
})
// setPostArray([{name: 'a'}, {name: 'b'},{name: 'c'}])
},[])
console.log(post)
return (
<div className="App">
{
post.map(item => <div>{item.title} </div>)
}
</div>
);
}
Here is the link to the example in codeSandBox: https://codesandbox.io/s/jovial-snow-773kp