Search code examples
reactjsreact-hooksaxiosuse-state

Get data from async function and update state


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?


Solution

  • 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 = [];