I’m consuming an API, my question is, how can I show only what the JSON has in position 0, for example.
If in my Promise
I have a console.log(res[0])
, it shows the first data, but if I have it here:
setDB(res[0]);
It is not working…
I’m very noob with React and I’m practising this… Sorry for the noob question.
What I want to do is to have a table where it only shows one data of the JSON
, and have two buttons to go next or prev… So I only need to show the first one.
This is How I’m consuming it:
function App() {
const [db, setDB] = useState(null)
const url = 'myAPI';
useEffect(() => {
generateRequest.get(url)
.then((res) => {
//console.log(res[0]); --> shows first data
setDB(res);
})
.catch(err => {
setDB([])
})
}, []);
return (
<>
{db && <Users db={db}/>}
</>
)
}
2
Answers
You are storing the fetched data using setDB(res), yet, you mentioned that you only want to show the first data from the JSON response and have buttons to navigate to the next or previous data.
You can modify your code as below. Please note that this code is so simplified. In usual, I would use a library such as MUI, etc.
In this updated code, there is a new state currentIndex (zero as initial value) that keeps track of the current index in the db array.
There are new methods handleNext and handlePrev, which update currentIndex accordingly to navigate to the next or previous data.
It seems like you may need to update your code to use
setDB(res[0])
instead ofsetDB(res)
. The former will retrieve the first record of the response body, which is typically what you want to display. Just be aware of this when working with the parameter inside the function.Additionally, I recommend using fetch() or Axios instead of generateRequest(). These methods are more commonly used. Also, they both require
json()
to parse the response body and access data elements.https://stackabuse.com/get-http-request-in-react/