UseEffecct is not getting the data from the API,it is showing null when I try to console........................................
import React, { useEffect, useState } from "react";
import axios from "axios";
export default function footerAjax() {
const [data, setData1] = useState('');
useEffect(async () => {
console.log("inerrrr");
axios
.get('https://jsonplaceholder.typicode.com/todos')
.then((res) => {
console.log("api --" JSON.stringify(res.data));
setData1(res.data);
});
},[]);
return (
<div className="app">
{console.log("footer == " JSON.stringify(data??{}))}
<FooterBody footerData={data??{}} />
</div>
);
}
CodePudding user response:
There are a couple of things to consider here that could be causing the issue:
The
useEffecthook is missing the dependency array, which tells React when to re-run the effect. This means that the effect will run on every render, causing multiple API calls and making the data unpredictable.setTimeoutdoes not return a promise, which makes theuseEffecthook return value not match the expected type. To resolve this, you can wrap the timeout code in aPromiseor usesetTimeoutinside the then block.axioshas not been imported in the code. You need to importaxiosto use it.
Here is the corrected code:
import React, { useEffect, useState } from "react";
import axios from 'axios';
export default function footerAjax() {
const [data, setData1] = useState(null);
useEffect(() => {
const fetchData = async () => {
console.log("inerrrr");
const res = await axios.get('https://jsonplaceholder.typicode.com/todos');
console.log("api --" JSON.stringify(res.data));
setData1(res.data);
};
fetchData();
}, []);
return (
<div className="app">
{console.log("footer == " JSON.stringify(data || {}))}
<FooterBody footerData={data || {}} />
</div>
);
}
<script type="text/babel">
// import React, { useEffect, useState } from "react";
// import axios from 'axios';
const { useEffect, useState } = React;
// Mocks
function FooterBody({ footerData }) {
return <pre>{JSON.stringify(footerData, null, 2)}</pre>;
}
// The URL mock is needed so the snippet works if the 3rd party URL ever goes down.
// https://jsonplaceholder.typicode.com/todos
const todosURL = URL.createObjectURL(new Blob(
[JSON.stringify([
{ "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false },
{ "userId": 1, "id": 2, "title": "quis ut nam facilis et officia qui", "completed": false },
{ "userId": 1, "id": 3, "title": "fugiat veniam minus", "completed": false }
])],
{ type: "application/json" }
));
// export default function footerAjax() {
function FooterAjax() {
const [data, setData1] = useState(null);
useEffect(() => {
const fetchData = async () => {
console.log("inerrrr");
const res = await axios.get(todosURL);
console.log("api --" JSON.stringify(res.data));
setData1(res.data);
};
fetchData();
}, []);
return (
<div className="app">
{console.log("footer == " JSON.stringify(data || {}))}
<FooterBody footerData={data || {}} />
</div>
);
}
ReactDOM
.createRoot(document.querySelector("#root"))
.render(<FooterAjax />);
</script>
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script crossorigin src="https://unpkg.com/axios@1/dist/axios.min.js"></script>
<script crossorigin src="https://unpkg.com/@babel/standalone@7/babel.min.js"></script>
<div id="root"></div>
CodePudding user response:
Also your react component name should begin with capital case.
CodePudding user response:
In your api does returns only array of objects. so it doesnot have key called data its becoming undefined. just remove data key it should work.
console.log("api --" JSON.stringify(res));
setData1(res);
hope this helps!!
CodePudding user response:
I can see multiple issues in the code snippet :
- Where is the dependencies array for the
useEffecthook ? - Why adding the
asynckeyword in bothuseEffectandsetTimeout? - In this line :
console.log("footer == " JSON.stringify(data??{}))I guess you meant :console.log("footer == ",JSON.stringify(data??{}))(same for the previous console.log) - Avoid using
setTimeoutif you don't need it - Import
axios
Try correcting these issues then build again.
