DEV Community

Liang Wang
Liang Wang

Posted on

Fetch data when empty

Earlier I had a task to use view model to fetch data, it worked well, but the problem is it loads data every time the view is loaded, it creates unnecessary amounts of network calls, and can even cause app to crash.

In the challenge I tried to finish, the advice was "Before you start your download, check that your array is empty so that you don’t keep starting the download every time the view is shown."

So to resolve this particular problem, I added a simple check like this and it works pretty well:

.task {
        if viewModel.arrayName.isEmpty {
          await viewModel.fetchData()
        }
      }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)