0

I am required to send some data from a view-only function to the front-end. I tried using the standard approach by emitting an event with the required fields. However, when the emit call is placed within a view type function, I get an error stating the emit call is potentially state-changing and, thus, cannot be within a view function.

How is data sent to the front-end by a View function if an event cannot be used?

event TestEvent (uint id);
function test() public view {
    emit TestEvent(123);
}

//Output
... TypeError: Function declared as view, but this expression (potentially) modifies the state and thus requires non-payable (the default) or payable.
...
1

An event is recorded (saved) on the blockchain, thus changing it.

So it can obviously not be emitted from a read-only (pure or view) function.

You can simply return the data, i.e., return 123;.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.