Skip to content

Commit 709ec34

Browse files
committed
Fix <FormattedRelative> auto-updating with strings
This fixes an issue where `<FormattedRelative>` would re-render every millisecond when `props.value` was a string (date timestamp). Now, `props.value` is passed into `new Date()` first, so a string value will be parsed.
1 parent 97aaa53 commit 709ec34

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

src/components/relative.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,8 @@ export default class FormattedRelative extends Component {
6969
return;
7070
}
7171

72-
let delta = Number(props.value) - state.now;
72+
let time = new Date(props.value).getTime();
73+
let delta = time - state.now;
7374
let units = props.units || selectUnits(delta);
7475

7576
let unitDelay = getUnitDelay(units);

test/unit/components/relative.js

+23
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,29 @@ describe('<FormattedRelative>', () => {
199199
}, 10);
200200
});
201201

202+
it('updates at maximum of `updateInterval` with a string `value`', (done) => {
203+
const {intl} = intlProvider.getChildContext();
204+
const date = new Date().toString();
205+
206+
// `toString()` rounds the date to the nearest second, this makes sure
207+
// `date` and `now` are equal.
208+
spyOn(intl, 'now').andCall(Date.now);
209+
210+
// Force scheduler by rendering twice with different props because
211+
renderer.render(<FormattedRelative value={date} updateInterval={10} />, {intl});
212+
213+
// Shallow Renderer doesn't call `componentDidMount()`.
214+
renderer.getMountedInstance().componentDidMount();
215+
216+
setTimeout(() => {
217+
// Make sure setTimeout wasn't called with `NaN`, which is like `0`.
218+
expect(intl.now.calls.length).toBe(1);
219+
220+
renderer.unmount();
221+
done();
222+
}, 10);
223+
});
224+
202225
it('does not update when `updateInterval` prop is falsy', (done) => {
203226
const {intl} = intlProvider.getChildContext();
204227
const date = new Date();

0 commit comments

Comments
 (0)