0

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
Shakeel
  • 21
  • 7

1 Answers1

0

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;
}
Wei Yan
  • 21
  • 2