'How to populate a div from the data from fetch
I am getting my output in a react app at this.state
but I want to bring this outside and populate div so that I can show it at the frontend. How can I do it?
fetch("https://flask-api-test1.herokuapp.com/predict", {
method: "post",
body: formData,
})
.then((res) => res.json())
.then((result) => {
console.log(state);
})
.catch((err) => {
console.log(err);
});
Solution 1:[1]
Your example is a bit incomplete. Anyways, here is how I would do that if the returned data was an array https://codesandbox.io/s/mutable-leftpad-o3v30?file=/src/App.js
Solution 2:[2]
If you can use hooks then the simplest solution is useState
import {useState} from 'react'
declare
const [newState, setNewState] = useState()
then you try
fetch("https://flask-api-test1.herokuapp.com/predict", {
method: "post",
body: formData,
})
.then((res) => res.json())
.then((result) => {
setNewState(result)
console.log(JSON.stringify(result));
})
.catch((err) => {
console.log(err);
});
and you can use ready-made 'newState' for div in jsx like
<div>
{newState?.keyDataYouNeed}
</div>
Solution 3:[3]
never do this.state
and assign values directly, as its immutable,
what you can do is ,
fetch("https://flask-api-test1.herokuapp.com/predict", {
method: "post",
body: formData,
})
.then((res) => res.json())
.then((result) => {
this.setState({data:result});
console.log(result);
})
.catch((err) => {
console.log(err);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 |