How to fetch data with stateless component in react?
How to get API value using axios in react?
Fetching data in the stateless component with react we need to use hooks as useEffect() and useState() hooks, and also using axios plugins.
Note: If your data is coming as a object then you need to use map() method other wise your data will not show. if you are as a string then use direct as variable.
This is simple example:
import React, { useEffect, use State } from 'react'
import axios from 'axios'
export default () => {
let [testVar, settestVar] = useState('');
useEffect( () => {
//.then(response => settestVar(response.data))
.then(response => cons ole.log(response.data))
}, [])
return(
<>
{testVar}
</>
)
}
................................................
const [userData, setUserData] = useState({});
useEffect(() => {
axios.get(apiBaseUrl + 'api/users')
.then(response => {
// how to set my value: response.data.data
setUserData(re sponse.data.data)
// console.log(re sponse.data.data)
}, error => {
console.log(er ror)
})
}, [])
.......................................................
import React, { useState, useE ffect } from 'react';
import axios from 'axios';
export default() => {const [data, setData] = useS
useEffect( () => {
.then(response => setData( response.data))
});
return (
<ul>
{data.hits.map(item => (
<li key={item.objectID }>
<a href={item.url}>{ item.title}</a>
</li>
))}
</ul>
);
}
I have used API only for the test purpose. You can use your own API.
No comments:
Note: Only a member of this blog may post a comment.