Skip to content
This repository was archived by the owner on Oct 19, 2018. It is now read-only.

Commit 833036c

Browse files
committed
Add set_state method
1 parent d5f3e15 commit 833036c

File tree

2 files changed

+27
-32
lines changed

2 files changed

+27
-32
lines changed

lib/react/component.rb

Lines changed: 15 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,15 @@ def mounted?
3838
`#{@native}.isMounted()`
3939
end
4040

41+
def set_state(state, &block)
42+
raise "No native ReactComponent associated" unless @native
43+
%x{
44+
#{@native}.setState(#{state.to_n}, function(){
45+
#{block.call if block}
46+
});
47+
}
48+
end
49+
4150
def component_will_mount
4251
self.run_callback(:before_mount)
4352
end
@@ -131,43 +140,18 @@ def define_state(*states)
131140
states.each do |name|
132141
# getter
133142
define_method("#{name}") do
134-
unless @native
135-
self.class.init_state[name]
136-
else
137-
`#{@native}.state[#{name}]`
138-
end
143+
return unless @native
144+
`#{@native}.state[#{name}]`
139145
end
140146
# setter
141147
define_method("#{name}=") do |new_state|
142-
unless @native
143-
self.class.init_state[name] = new_state
144-
else
145-
%x{
146-
state = #{@native}.state || {};
147-
state[#{name}] = #{new_state};
148-
#{@native}.setState(state);
149-
}
150-
end
151-
152-
new_state
153-
end
154-
# setter with callback
155-
define_method("set_#{name}") do |new_state, &block|
156-
unless @native
157-
self.class.init_state[name] = new_state
158-
else
159-
%x{
160-
state = #{@native}.state || {};
161-
state[#{name}] = #{new_state};
162-
#{@native}.setState(state, function(){
163-
#{block.call if block}
164-
});
165-
}
166-
end
148+
return unless @native
149+
hash = {}
150+
hash[name] = new_state
151+
self.set_state(hash)
167152

168153
new_state
169154
end
170-
171155
end
172156
end
173157
end

spec/component_spec.rb

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ def render
9090
it "should allow block for life cycle callback" do
9191
Foo.class_eval do
9292
define_state(:foo)
93-
93+
9494
before_mount do
9595
self.foo = "bar"
9696
end
@@ -193,6 +193,17 @@ def render
193193
expect(element.getDOMNode.textContent).to eq("10")
194194
end
195195

196+
it "should support original `set_state` method" do
197+
Foo.class_eval do
198+
before_mount do
199+
self.set_state(foo: "bar")
200+
end
201+
end
202+
203+
element = renderToDocument(Foo)
204+
expect(element.state.foo).to be("bar")
205+
end
206+
196207
pending "should set initial state in Class#initialize method" do
197208
Foo.class_eval do
198209
define_state :foo, :bar

0 commit comments

Comments
 (0)