Reactive OWL Component
Reactivity's objective is to offer a straightforward method of changing the state in a way that causes the interface to be updated automatically as the state changes. Through the hooks, OWL supports automatic user interface updating. The hooks will automatically update the component's UI when a change is made to the component's internal state. The message in the component will be updated in the example that follows based on the user's actions.
Making our OWL component reactive by carrying out the subsequent actions, the useState hook import
const { Component, whenReady, xml, mount, useState } = owl;
Then define the component as below:
class Counter extends Component {
static template = xml`
<div class="bg-info text-center p-2">
<i class="fa fa-arrow-left p-1" style="cursor: pointer;" t-on-click="onPrevious"> </i>
<b t-esc="messageList[Math.abs(state.currentIndex%4)]"/>
<i class="fa fa-arrow-right p-1" style="cursor: pointer;" t-on-click="onNext"> </i>
<i class="fa fa-close p-1 float-right" style="cursor: pointer;" t-on-click="onRemove"> </i>
</div>`
}
Then add the constructor () method for constructor
constructor() {
super(...arguments);
this.messageList = [
'Hello World',
'Welcome to Odoo',
'Odoo is awesome',
'You are awesome too'
];
this.state = useState({ currentIndex: 0 });
}
Inside the component, we define the methods for handling click events as shown below:
onNext(ev) {
this.state.currentIndex++;
}
onPrevious(ev) {
this.state.currentIndex--;
}
Here, we imported the useState hook to handle the state of the component. Then define the template of the component. In the component we have added message with an arrow on both the left and right side of the message. The constructor method is called when the instance of the object is created. Inside the constructor, we have defined list of the message to a variable. Using the useState hook, we have added state variable. Thus our OWL component is reactive. We have added the current index in the state; when a change happens to the state, UI is also updated. The methods onNext() and onPrevious() are used to update the variable. The output will be as shown below:
When we click on the arrow, the corresponding method is called and updates the message.