Skip to content

Commit

Permalink
Merge pull request #526 from fleur-js/fix-shallow-equality-mismatch
Browse files Browse the repository at this point in the history
Fix shallow equaled objects judged to not shallow equals
  • Loading branch information
hanakla authored Apr 17, 2022
2 parents 1a3b4aa + 1814c55 commit 928fe42
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
16 changes: 15 additions & 1 deletion packages/react/src/useStore.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,23 @@ import Fleur, {
import * as React from 'react'
import { renderHook, act } from '@testing-library/react-hooks'

import { useStore } from './useStore'
import { isEqual, useStore } from './useStore'
import { FleurContext } from './ComponentReactContext'

describe('isEqual', () => {
it('equals', () => {
expect(isEqual(1, 1)).toBe(true)
expect(isEqual([1, 2, 3], [1, 2, 3])).toBe(true)
expect(isEqual({ a: 1, b: 2 }, { a: 1, b: 2 })).toBe(true)
})

it('not equals', () => {
expect(isEqual(1, 2)).toBe(false)
expect(isEqual([1, 2, 3], [3, 2, 1])).toBe(false)
expect(isEqual({ a: 1, b: 2 }, { a: 1, b: null })).toBe(false)
})
})

describe('useStore', () => {
// Action Identifier
const ident = action<{ increase: number }>()
Expand Down
6 changes: 5 additions & 1 deletion packages/react/src/useStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ const is = (x: any, y: any): boolean => {
}

/** Shallow equality check */
const isEqual = (prev: any, next: any) => {
export const isEqual = (prev: any, next: any) => {
if (is(prev, next)) return true
if (typeof prev !== typeof next) return false

Expand All @@ -53,6 +53,8 @@ const isEqual = (prev: any, next: any) => {
for (const idx in prev) {
if (!is(prev[idx], next[idx])) return false
}

return true
}

if (
Expand All @@ -65,6 +67,8 @@ const isEqual = (prev: any, next: any) => {
if (!hasOwnKey.call(next, key)) continue
if (!is(prev[key], next[key])) return false
}

return true
}

return false
Expand Down

0 comments on commit 928fe42

Please sign in to comment.