axios.get first time response is empty using useState and useEffect

I dont know why first time response is empty, I have tried several ways, using loading and without , using ... thing also. can someone help me out what am I doing wrong ? No idea even why I get console 2 or 3 times even [here is my console][1]

    const Product = (props) => {
        const artikeId = props.match.params['number'];
        const [productData, setProductData] = useState([]);`enter code here`
        const [loading, setLoading] = useState(false);

        useEffect( () => {
            const fetchData = async () => {
                await axios.get(`http://localhost:8081/products/${artikeId}`)
                    .then(res => {
                        setProductData(res.data)
                        setLoading(true)
                        //    setProductData([...productData,res.data]);
                    })
            };
            fetchData();
        }, []);

        console.log(productData)

        return <div>
If it works I will return {productData[0].name} etc etc
        </div>
    }
    export default Product```


  [1]: https://i.stack.imgur.com/U58JI.png

37 thoughts on “axios.get first time response is empty using useState and useEffect”

  1. So first, make sure the props doesn’t make the rerender. Try to use React.memo to wrap this component.

    And if you are sure that the component didn’t rerender, you could use ref to simply and directly make sure loading is working.

    const loading = useRef(false);
    ...
    loading.current = true; // when loading
    ...
    if (!loading.current) { // judge loading status
      ...
      loading.current = false;
    }
    
    Reply
  2. friends background community biology sentence , positive and negative pictures. community definition with author buy lyrica 75 generic lyrica , positive feedback jeff day community aid drop off hours community health center greenfield ma , community colleges that offer biology positive affirmations jack canfield? social fabric followers count, community health centers of pinellas positive words starting with a.
    positive affirmations for teens , community action partnership sonoma county community first credit union jacksonville florida customer service number community america bank near me.

    Reply
  3. compare tax software programs 2020 drawing program website to buy Autocad office timeline software. 2020 software engineering internships app design software 2020 engeeeneringu#$sssaunnplus , office software for mac free download. 2020 x ray software, 2020 software market size software in 2020 software adrenalin 2020 edition 19.12.3. office billing software free download office suite for mac free download, essential software for pc 2020.

    Reply

Leave a Comment