-2

If I use a variable instead of using react state object inside a function is behaving weirdly for fetch. If i remove the const response..... and const data.... line things works just fine but If i use fetch function and use normal variable without using state this doesn't work. Why is that?

Object is showing normal if i log it from inside the function

Object is also showing normal if i use const variable

Object is showing like an empty object if i log it from outside the function

But this code works just fine..

   const [services, setServices] = useState([]);

   useEffect(() => {
    const API_URL = "http://localhost:8080/getServiceName/3";

    const loadData = async () => {
        const apiData = [];
        const response = await fetch(API_URL);
        const data = await response.json();

        data.services.map(service => (
            apiData.push(service.service_name)
        ));
        setServices(apiData);
    }
    loadData();
   }, [location])

And notice that i can add more value to a const variable(const dummyLocation{in image} and const apiData in code)!, How??

  • Please edit your question and describe specifically what did you get on each attempt – GalAbra Aug 08 '20 at 09:18
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – jonrsharpe Aug 08 '20 at 09:20
  • You yourself showing that it does have data in console.log , when you try to expand the Object. It is showing blank in non-expanded view because console.log was synchronous and at the time of execution it did not contain any data. When asynchronous called get resolved , it filled dummyLocation with all the data. – devd Aug 08 '20 at 09:25

1 Answers1

-1

loadData(); is asynchronous, so if you do

loadData()
console.log(dummyLocation)

then the console.log will happen before loadData completed. You probably just want to do

loadData().then(() => console.log(dummyLocation))

As for the questions regarding why you can do:

const apiData = [];
// ...
apiData.push(service.service_name)

the reason is that const doesn't mean the variable can't change (per se), but instead that the variable will never be reassigned - you can't do:

const apiData = [];
apiData = [service.service_name];

because that is assigning a new array to it.

dave
  • 62,300
  • 5
  • 72
  • 93
  • So when i use state it check if the value changed or not and it keeps the update so that's why i can go with state in this case? – Shahriar Dhruvo Aug 08 '20 at 10:56