Why will my fetch API call map one nested objects, but not the other? - javascript

I'm parsing data from the NASA API using React, and for some reason I can map one nested object within the return but not the other.
Here is my parent component:
import React, { useState } from 'react'
import './NasaAPI.scss'
import NasaImages from './NasaImages'
const NasaAPI = () => {
const [nasaData, setNasaData] = useState([])
const [nasaImage, setNasaImage] = useState("")
const [searchInput, setSearchInput] = useState("")
const [loading, setLoading] = useState(true)
const fetchData = async (e) => {
const data = await fetch(`https://images-api.nasa.gov/search?q=${searchInput}`)
.then(response => response.json())
.then(data => setNasaData(data.collection.items))
.catch(err => console.log(err))
.finally(setLoading(false))
}
const handleSubmit = (e) => {
e.preventDefault()
fetchData()
}
const handleChange = (e) => {
setSearchInput(e.target.value)
}
return (
<div>
<h2>Search NASA Images</h2>
<form onSubmit={handleSubmit}>
<input name="searchValue" type="text" value={searchInput} onChange={handleChange}></input>
<button value="Submit">Submit</button>
</form>
<section>
<NasaImages nasaData={nasaData} loading={loading}/>
</section>
</div>
)
}
export default NasaAPI
Here's where the issue is, in the child component:
import React from 'react'
const NasaImages = ({ nasaData }) => {
console.log(nasaData)
return (
<div>
<h2>This is a where the data go. 👇</h2>
{
nasaData && nasaData.map((data, idx) => {
return (
<div key={idx}>
<p>{data.href}</p>
<div>
{/* {data.links.map((data) => {
return <p>{data.href}</p>
})} */}
{data.data.map((data) => {
return <p>{data.description}</p>
})}
</div>
</div>
)
})
}
</div>
)
}
export default NasaImages
The current configuration works, and will display a data.description (data.data.map) mapping property. However, I want the commented code immediately above it to work which displays a data.href (data.links.map) property.
The JSON looks as follows:
So, the issue is that I can map one set of properties, data.data.map, but cannot access the other in the same object, data.links.map, without getting the error "TypeError: Cannot read property 'map' of undefined". Thank you in advance!

There exists a data element sans a links property, in other words there is some undefined data.links property and you can't map that. Use Optional Chaining operator on data.links when mapping, i.e. data.links?.map. Use this on any potentially undefined nested properties.
const NasaImages = ({ nasaData = [] }) => {
return (
<div>
<h2>This is a where the data go. 👇</h2>
{nasaData.map((data, idx) => (
<div key={idx}>
<p>{data.href}</p>
<div>
{data.links?.map((data, i) => <p key={i}>{data.href}</p>)}
{data.data?.map((data, i) => <p key={i}>{data.description}</p>)}
</div>
</div>
))}
</div>
)
}

Related

Add item from Fetch API to Array and Displaying new array in React

I'm learning react for the first time, I have an app where it fetches some data from a public API. I currently have it show 10 cards with random items from the API, and I have added a button to fetch a random item from the API and add it to the array, I managed to get the new item added to the array using push() but it does not show in the app itself. How can I make it that the new item is shown in the app as well?
Here is my code
Home.js
import { useState, useEffect} from "react";
import Card from './Card';
const Home = () => {
const [animals, setAnimals] = useState([]);
const handleDelete = (id) => {
const newAnimals = animals.filter(animal => animal.id !== id);
setAnimals(newAnimals);
}
useEffect(() => {
fetch('https://zoo-animal-api.herokuapp.com/animals/rand/10')
.then(res => {return res.json()})
.then(data => {
setAnimals(data);
});
}, []);
const handleAddAnimal = () => {
fetch('https://zoo-animal-api.herokuapp.com/animals/rand/')
.then(res => {return res.json()})
.then(data => {
animals.push(data);
console.log(animals);
//what to do after this
})
}
return (
<div className="home">
<h2>Animals</h2>
<button onClick={handleAddAnimal}>Add Animal</button>
<Card animals={animals} handleDelete={handleDelete}/>
</div>
);
}
export default Home;
Card.js
const Card = ({animals, handleDelete}) => {
// const animals = props.animals;
return (
<div className="col-3">
{animals.map((animal) => (
<div className="card" key={animal.id}>
<img
src={animal.image_link}
alt={animal.latin_name}
className="card-img-top"
/>
<div className="card-body">
<h3 className="card-title">{animal.name}</h3>
<p>Habitat: {animal.habitat}</p>
<button onClick={() => handleDelete(animal.id)}>Delete Animal</button>
</div>
</div>
))}
</div>
);
}
export default Card;
App.js
import Navbar from './navbar';
import Home from './Home';
function App() {
return (
<section id="app">
<div className="container">
<Navbar />
<div className="row">
<Home />
</div>
</div>
</section>
);
}
export default App;
Screenshot of what I see now
screenshot
(I was also wondering how to fix the items going down instead of side by side but wanted to fix the add button first)
Let me know if there's anything else I should add, any help is appreciated, thank you!
Rather using array.push() method. You try using
setTheArray([...theArray, newElement]); e.g in your case it will be setAnimals([...animals,data]) in your onClick event.
Let me know doest it solve your issue or not.
const handleAddAnimal = () => {
fetch('https://zoo-animal-api.herokuapp.com/animals/rand/')
.then(res => {return res.json()})
.then(data => {
setAnimals([...animals,data])
console.log(animals);
//what to do after this
})
}

How can I display the results of map function in jsx?

I'm slowly learning react and trying to display the results of my searchMap function (movie title/poster) with the TMDB API. I can log the information I need to the console, but I get undefined variables and other errors when trying to display the information in the commented div.
https://codesandbox.io/s/ddmdu4
function App() {
const search = async (event) => {
const searchQuery = event.target.value;
if (searchQuery) {
const searchReq = await fetch(
`https://api.themoviedb.org/3/search/movie?api_key=${process.env.API_KEY}&query=${searchQuery}`
).then((res) => res.json());
const searchResults = searchReq.results;
searchMap(searchResults);
}
};
const searchMap = (searchResults) => {
searchResults.map((movie) => {
console.log(`${movie.title}`);
console.log(`${movie.backdrop_path}`);
});
};
return (
<div className="App">
<div>
<input type="text" onChange={search} placeholder="Search"></input>
</div>
<div>{/* Display movie title/poster*/}</div>
</div>
);
}
export default App;
Since you want to update the DOM each time the result changes I would recommend using that inside of a state like so:
const [searchResults, setSearchResults] = React.useState([]);
In your async search function update the state by using its appropiate "setter":
.then((res) => res.json());
setSearchResults(searchReq.results);
And inside your return you can map the result as follows:
<div>
{searchResults.map((movie) => (
<>
<div>{movie.title}</div>
<div>{movie.backdrop_path}</div>
</>
))}
</div>

Rendering nested object properties from API call in react

I am trying to render text from an API call, text or numbers that are directly accesible from the axios.data object can render normally, nevertheless when inside the axios.data there is another object with its own properties I cannot render because an error shows, the error is 'undefined is not an object (evaluating 'coin.description.en')', over there description is an object; my code is
function SINGLE_COIN(props) {
const { id } = useParams()
console.log(id);
const SINGLE_API = `https://api.coingecko.com/api/v3/coins/${id}?tickers=true&market_data=true&community_data=true&developer_data=true&sparkline=true`
const [coin, setCoin] = useState({})
useEffect(() => {
axios
.get(SINGLE_API)
.then(res => {
setCoin(res.data)
console.log(res.data)
})
.catch(error => {
console.log(error)
})
}, [])
return (
<div>
<h2>{coin.name}</h2>
<div>{coin.coingecko_score}</div>
<div>{coin.liquidity_score}</div>
<div>{coin.description.en}</div>
<SINGLE_COIN_DATA coin={coin} />
</div>
)
}
Thanks!
For the initial render (data is not fetched yet), it will be empty. so nested property would be undefined.
so note the changes:
Example 1:
const [coin, setCoin] = useState(null);
..
return (
<div>
{coin ? (
<>
<h2>{coin.name}</h2>
<div>{coin.coingecko_score}</div>
<div>{coin.liquidity_score}</div>
<div>{coin.description.en}</div>
</>
) : null}
</div>
);
Example:2: Use the optional chaining while accessing nested property
return (
<div>
<h2>{coin?.name}</h2>
<div>{coin?.coingecko_score}</div>
<div>{coin?.liquidity_score}</div>
<div>{coin?.description?.en}</div>
</div>
);
And the complete code with : working example
export default function SINGLE_COIN() {
const { id } = useParams()
const SINGLE_API = `https://api.coingecko.com/api/v3/coins/${id}?tickers=true&market_data=true&community_data=true&developer_data=true&sparkline=true`;
const [coin, setCoin] = useState(null);
useEffect(() => {
axios
.get(SINGLE_API)
.then((res) => {
setCoin(res.data);
})
.catch((error) => {
console.log(error);
});
}, []);
return (
<div>
{coin ? (
<>
<h2>{coin.name}</h2>
<div>{coin.coingecko_score}</div>
<div>{coin.liquidity_score}</div>
<div>{coin.description.en}</div>
</>
) : null}
</div>
);
}

I am unable to access Json data and display it in table using axios in React

I am trying to access json data using hooks and display it in the tag but it is showing error-"TypeError: states.map is not a function".I also used Array.from() to convert my json to array and it did not showed any error but also did not display anything.
var rows=[{}];
export default function Mainpage() {
const [states, setstate] = useState([]);
const getLatestJSPost = () => {
const API_URL = "http://localhost:8080/Displaydo";
axios
.get(API_URL)
.then((response) => {
// rows = Array.from(response.data);
console.log(response.data);
setstate(response.data)
})
};
useEffect(() => {
getLatestJSPost();
}, [])
return (
<div>
<p>Hello</p>
{ states.map((ndata) => {
return <p key={ndata.doc_id}> {ndata.doc_id} </p>
})}
</div>
)
}
The conole.log(response.data) looks like
Output of console.log(response.data)
you can do it this way:
<div>
<p>Hello</p>
{states.length>0 && states.map((ndata) => {
return <p key={ndata.doc_id}> {ndata.doc_id} </p>
})}
</div>

How to map over a response from a REST call? [duplicate]

This question already has answers here:
what is right way to do API call in react js?
(14 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I have the following code where I am making a REST call and assigning the result to a variable.
Then I am using the result to map over and create components with props.
But at present it throws an error because the value for list is undefined.
I believe this is because the value of the list is not set yet when I am attempting to map due to axios async call not completed yet.
Thus 2 queries.
How should I use the response value. Is my method of assigning it to the variable 'list' correct or it should be done differently?
How do I wait for list to be populated and then map over it?
You can see how the response.data will look by looking at following endpoint: https://sampledata.free.beeceptor.com/data1
Sample response data:
[
{
"word": "Word of the Day",
"benevolent": "be nev o lent",
"adjective": "adjective",
"quote": "well meaning and kindly.<br/>a benevolent smile",
"learn": "LEARN MORE"
},
{
"word": "Word of the Day",
"benevolent": "be nev o lent",
"adjective": "adjective",
"quote": "well meaning and kindly.<br/>a benevolent smile",
"learn": "LEARN MORE"
}
]
Client code:
const App = () => {
// const cardData = useSelector(state => state.cardData)
let list;
useEffect(() => {
axios.get('https://sampledata.free.beeceptor.com/data1')
.then(response => {
list = response.data;
list.forEach(l => console.log(l))
})
.catch(error => {
console.log(error)
})
}, [])
return (
<>
<ButtonAppBar/>
<div className='container'>
<div className='row'>
{
list.map((data) => {
const {word, bene, adj, well, learn} = data;
return (
<div className='col-lg-3 col-md-6 format'>
<SimpleCard word={word} bene={bene} adj={adj} well={well} learn={learn} />
</div>
)
})
}
</div>
</div>
</>
);
}
export default App;
You need to make use of useState to store the data that you get from the API.
For example
const [state, setState] = useState({ list: [], error: undefined })
Because the API call is asynchronous and the data will not be available until the component mounts for the first time. You need to use a conditional to check for state.list.length otherwise it will throw an error cannot read property ..x of undefined.
const App = () => {
// create a state variable to store the data using useState
const [state, setState] = useState({ list: [], error: undefined });
useEffect(() => {
axios
.get("https://sampledata.free.beeceptor.com/data1")
.then(response => {
setState(prevState => ({
...prevState,
list: [...prevState.list, ...response.data]
}));
})
.catch(error => {
setState(prevState => ({ ...prevState, list: [], error: error }));
});
}, []);
return (
<>
<ButtonAppBar/>
<div className='container'>
{
// you can show a loading indicator while your data loads
!state.list.length && <div>The data is loading....</div>
}
<div className='row'>
{
state.list.length && state.list.map((data) => {
const {word, bene, adj, well, learn} = data;
return (
<div className='col-lg-3 col-md-6 format'>
<SimpleCard word={word} bene={bene} adj={adj} well={well} learn={learn} />
</div>
)
})
}
</div>
</div>
</>
);
}
You could benefit from using useState hook here.
For example:
const App = () => {
const [list, setList] = useState([]);
useEffect(() => {
axios.get('https://sampledata.free.beeceptor.com/data1')
.then(response => {
setList(response.data);
})
.catch(error => {
console.log(error)
})
}, [])
return (
<>
<ButtonAppBar/>
<div className='container'>
<div className='row'>
{
list.map((data) => {
const {word, bene, adj, well, learn} = data;
return (
<div className='col-lg-3 col-md-6 format'>
<SimpleCard word={word} bene={bene} adj={adj} well={well} learn={learn} />
</div>
)
})
}
</div>
</div>
</>
);
}
export default App;
Do not use let to save fetched values instead use state or props in case you want to generate UI from that. In react component rerender if state or props value changed.
Reason of getting error is, you are doing asynchronous call and because of that your component is parallely rendering and inside the return list will be null and it will throw error .
Correct way is :
const App = () => {
const [list, setlist]= React.useState([])
useEffect(() => {
axios.get('https://sampledata.free.beeceptor.com/data1')
.then(response => {
setlist (response.data)
})
.catch(error => {
console.log(error)
})
}, [])
return (
<>
<ButtonAppBar/>
<div className='container'>
<div className='row'>
{
list.map((data) => {
const {word, bene, adj, well, learn} = data;
return (
<div className='col-lg-3 col-md-6 format'>
<SimpleCard word={word} bene={bene} adj={adj} well={well} learn={learn} />
</div>
)
})
}
</div>
</div>
</>
);
}
export default App;
This can be solved in two ways (since you are using hooks)
useRef() (I would not recommend doing this)
useState() (as the example I have given)
I will show you by using the useState method, but you should keep in mind that since it's a state it will re-render (I don't think it will be an issue here).
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const App = () => {
let [list, setList] = useState(<>LOADING</>);
useEffect(() => {
// You can use your link here
// I have created corsenabled.herokuapp.com just to bypass the CORS issue. It's only for testing and educational purpose only. No intention to infringe any copyrights or other legal matters
// I have used jsonplaceholder.typicode.com as an example
axios.get('https://corsenabled.herokuapp.com/get?to=https://jsonplaceholder.typicode.com/posts')
.then(response => {
let tempData = response.data;
let anotherData = tempData.map(data => {
return (<div>{data.userId}<br/>{data.id}<br/>{data.title}<br/>{data.body} <br/><br/></div>)
})
// tempData = tempData.map(data => <div> {JSON.stringify(data)} </div>)
console.log(tempData)
setList(anotherData)
})
.catch(error => {
console.log(error)
})
}, [])
return (
<>
<div className='container'>
<div className='row'>
{
list
}
</div>
</div>
</>
);
}
export default App;

Categories

Resources