Using react.js, I'm trying to fetch data from an API using the code below:
import React,{useState,useEffect} from 'react';
function App() {
const [data,setData]=useState([]);
const getData=()=>{
fetch('src/data.json')
.then(function(response){
return response.json();
})
.then(function(myJson) {
setData(myJson)
});
}
useEffect(()=>{
getData()
},[])
return (
<ul>
{data.map((item) =>
<li key={item.id}>{item.name}</li>
)}
</ul>
);
}
export default App;
and api json response is (sample from data.json):
{"users":
[{"id":1,"name":"John"},{"id":2,"name":"Samantha"}]
}
If I remove the object {"users": } then the code works, but API adds this object to all endpoints.
Is there a way to ignore that first object, or to de-structure it so I get an output of:
If your Javascript interpreter is up to date you can try using the spread operator.
object = {"users":
[{"id":1,"name":"John"},{"id":2,"name":"Samantha"}]
};
object = {...object.users};
Result:
{
0: {id: 1, name: 'John'},
1: {id: 2, name: 'Samantha'}
}
More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax