I am able to to display the data in the console but unable to display the same in the DOM page using react . I have seen this problem but none of the answers actually work for me .Can you please tell me where I am going . Am I accessing the wrong info in SetData()
function Test() {
const [loading, SetLoading] = useState(false);
const [questions, SetData] = useState(null);
const getData = async () => {
try {
const info = await axios.get("http://localhost:3000/info").then((res) => {
console.log(res);
SetData(res.data.info);
});
SetLoading(true);
} catch (err) {
console.log(err);
}
};
useEffect(() => {
getData();
}, []);
return <div>{loading ? questions : <ReactBootstrap.Spinner animation="border" variant="success" />}</div>;
}
export default Test;
API data format :
{
"info": [
{
"question": "Angular 2 integrates easily with NativeScript, allowing you to code your native app in a . . . . . . . . . style that can run on any mobile device platform.",
"options": ["a) declarative", "b) imperative", "c) interrogative", "d) exclamatory"],
"answer": 0,
"id": 0
},
{
"question": "Angular 2 components can be described using ________is a way to do some meta-programming.",
"options": [
"a) controllers, controller",
"b) Loaders, loader",
"c) typescripts, typescript",
"d) decorators, decorator"
],
"answer": 3,
"id": 1
},
{
"question": "The ______ directive substitutes the normal href property and makes it easier to work with route links in Angular 2.",
"options": ["a) RouterLink", "b) RouterRend", "c) RouterLike", "d) RouterLayer"],
"answer": 0,
"id": 2
}
]
}
screenshot of the react page for more clarity
CodePudding user response:
You are setting data into "then" function with await, so, first set the data, and after set loading in true, now your loading keep in screen.
You need set first the loading and after that set the data.
CodePudding user response:
The response you are getting from your API call includes an array called data
. You are treating res.data
as an object by attempting to access res.data.info
. This will return undefined and thus you are never updating your questions
state. I've rewritten your code below. I hope this will work (if it doesn't, it's a step in the right direction). I have also changed it such that when getData()
is called, the first thing that happens is loading
is set to true, then the API call is made, then loading
is set back to false.
function Test() {
const [loading, setLoading] = useState(true);
const [questions, setQuestions] = useState();
const getData = async () => {
try {
setLoading(true)
await axios.get("http://localhost:3000/info").then(res => {
setQuestions(res.data);
setLoading(false);
});
} catch (err) {
console.log(err);
}
};
useEffect(() => {
getData();
}, []);
return <div>
{loading ? <ReactBootstrap.Spinner animation="border" variant="success" /> : questions}
</div>;
}
export default Test;
CodePudding user response:
try using res.info instead of res.data.info