sanzaru/SimpleToast

Toast not showing asynchronously fetched content

sanzaru opened this issue · 1 comments

In case the content of the toast is fetched asynchronously, it is not being displayed inside the toast and instead just trigger an empty toast. Debugging the request shows that the content was fetched correctly, but is empty inside the toast view.

Example:

...

@State private var asyncMessage: String = ""

... 

Button("Trigger async action") {
    withAnimation {
        let url = URL(string: "https://jsonplaceholder.typicode.com")!
        URLSession.shared.dataTask(with: url) { data, response, error in
            DispatchQueue.main.async {
                asyncMessage = String(data: data!, encoding: .utf8)!
                print(asyncMessage)
                showToastAsync = !asyncMessage.isEmpty
            }
        }
        .resume()
    }
}

... 

.simpleToast(isShowing: $showToastAsync, options: optionsScale) {
    Text(asyncMessage)
}

Closed as this bug does not come from the library itself, but how swift handles asynchronous content. Triggering the boolean outside the closure of URLSession works fine:

Button("Trigger async action") {
    withAnimation {
        let url = URL(string: "https://jsonplaceholder.typicode.com")!
        URLSession.shared.dataTask(with: url) { data, response, error in
            DispatchQueue.main.async {
                asyncMessage = String(data: data!, encoding: .utf8)!
            }
        }
        .resume()

        showToastAsync.toggle()
    }
}