The following sample data will be coming from backend API call. The backend is flask and the API is already in place at the backend.
const rows = [
{
name: "XYZ",
age: "12",
email: "[email protected]"
},
{
name: "David",
age: "13",
email: "[email protected]"
},
{
name: "abc",
age: "12",
email: "[email protected]"
}
]
How can I integrate the backend API with React? I'm new to react, so I don't know how should I proceed.
CodePudding user response:
You can use axios for sending api requests.
const [state,setState] = useState()
useEffect(()=>{
axios.get(url)
.then(res=>setState(res.data))
.catch(err=>console.log(err))
},[])
CodePudding user response:
In React you'll have to use two hooks - useState
and useEffect
. The first one will help you keep the data so you can use it and the second one will help you getting it.
function Component() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('your endpoint here').then(res => {
if (res.status === 200) {
return res.json();
} else {
// handle error
}
}).then(data => {
setData(data);
}).catch(err => {
// handle error
})
}, []);
if (data !== null) {
return <p>Data is here {data.length}</p>;
}
return <p>Loading the data</p>;
}
And just to clarify that we need to use useEffect
so we fire the request only once when the component is mounted. This is the effect of using []
for the dependencies' list as a second argument to the hook.