1

I have created a variable using useState and that is an empty array.

const [data, setData] = useState([]);

I am calling an async function inside useEffect that is helping me to get all the data and update the data when received

useEffect(() => {
    //
    const items = [];
    async function fetchData() {
      items = await getAllItems();   //it should wait for data and then setData
      setData(items);    
    }
    fetchData();
    console.log("from useEffect", items);  // still items array is empty
  }, []);

Here is my imported data retrieving function which uses Axios and returns the data:

export const getAllItems = async () => {
  const url = baseUrl + "/items/getAllItems";
  await axios({
    method: "GET",
    withCredentials: true,
    url: url,
  }).then((res) => {
    return res;  // when console logged we get a proper array if data
  });
};

But nothing works all I am getting back is object of promise. Could anyone guide me what I am missing out in my code?

8
  • Setstate is asynchronously, you can not see updated data in console log after setstate. Use useEffect dependency for updated data Commented Apr 16, 2022 at 12:23
  • I have tried making this call outside useEffect and then updating it in useEffect but that also not works Commented Apr 16, 2022 at 12:26
  • Can you see items in console log before setData(items)?? Commented Apr 16, 2022 at 12:31
  • 1
    Change const items to let items. Commented Apr 16, 2022 at 12:45
  • 1
    Check is your api response array or object, then write some condition in html. If data have then map Commented Apr 16, 2022 at 13:00

4 Answers 4

3

You are assigning the value of getAllItems() to a constant variable items that has already been declared here:

const items = [];

However, as per the mdn web docs:

The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration).

So you need to either initialize that variable using let, or better yet assign it immediately as follow:

const items = await getAllItems();

You can then get rid of const items = [];

Sign up to request clarification or add additional context in comments.

6 Comments

I messed up with my jsx syntax thats why it was creating an issue. Could you please add some explanation as it will help others .
we can use this or declare items as let that will also help and to stop re rendering in endless loop remove the name of variable from the useEffect array or else it will keep on re rendering infinite times
@Ashishsah Did my answer allow to solve your problem by itself or was there some other issue that needs to be included as well ?
well I guess there were few mistakes by my side. Well I am editing your answer.
@Ashishsah I added explanations to the point mentioned in my answer. Feel free to add more to it if needed.
|
0

You didn't return the data from the axios call.

export const getAllItems = async () => {
  const url = baseUrl + "/items/getAllItems";
  const { data } = await axios({
    method: "GET",
    withCredentials: true,
    url: url,
  });
  return data;
};

2 Comments

that is not working
if you console.log items before setData is called what is shown?
0

Your console.log() is in the wrong position (2). Should be in the position marked with (1) instead. Please check the comments I added:

useEffect(() => {
    const items = [];
    async function fetchData() {
      items = await getAllItems();   //it should wait for data and then setData
      setData(items);
      // (1) you chould console.log() the items array here instead
      // if the data is properly returned from getAllItems() it will be visible here
      console.log("from useEffect", items);
    }
    fetchData();
    console.log("from useEffect", items);  // (2) items array will be empty here right after fetchData() as getAllItems() has not returned yet.
  }, []);

3 Comments

Uncaught (in promise) TypeError: Assignment to constant variable. this is what i get
Try changing const items = [] to let items = []. Like the error says you cannot reassign a const variable (although you can e.g. .push() to it, here it will be completely reassigned).
Or even better: do what @monstar said and assign directly to const.
0
useEffect(() => {
   let isMounted = true 
   function fetchData() {
      const items = axios.get(baseUrl + "/items/getAllItems")
      if (isMounted) setData(items);    
   }
   fetchData();
   return () => {isMounted = false}
}, []);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.