Home > Blockchain >  useEffect is not working in functional component,showing null data
useEffect is not working in functional component,showing null data

Time:02-03

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:

  1. The useEffect hook 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.

  2. setTimeout does not return a promise, which makes the useEffect hook return value not match the expected type. To resolve this, you can wrap the timeout code in a Promise or use setTimeout inside the then block.

  3. axios has not been imported in the code. You need to import axios to 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 :

  1. Where is the dependencies array for the useEffect hook ?
  2. Why adding the async keyword in both useEffect and setTimeout ?
  3. 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)
  4. Avoid using setTimeout if you don't need it
  5. Import axios

Try correcting these issues then build again.

  • Related