Skip to content

Commit

Permalink
fix(hooks): do not accept undefined as initial values (#1398)
Browse files Browse the repository at this point in the history
  • Loading branch information
silviuaavram authored Aug 11, 2022
1 parent eac25d3 commit 1054249
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 9 deletions.
40 changes: 39 additions & 1 deletion src/hooks/__tests__/utils.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import {getItemIndex, defaultProps} from '../utils'
import {
getItemIndex,
defaultProps,
getInitialValue,
getDefaultValue,
} from '../utils'

describe('utils', () => {
describe('itemToString', () => {
Expand All @@ -25,4 +30,37 @@ describe('utils', () => {
expect(index).toBe(1)
})
})

test('getInitialValue will not return undefined as initial value', () => {
const defaults = {bogusValue: 'hello'}
const value = getInitialValue(
{initialBogusValue: undefined},
'bogusValue',
defaults,
)

expect(value).toEqual(defaults.bogusValue)
})

test('getInitialValue will not return undefined as value', () => {
const defaults = {bogusValue: 'hello'}
const value = getInitialValue(
{bogusValue: undefined},
'bogusValue',
defaults,
)

expect(value).toEqual(defaults.bogusValue)
})

test('getDefaultValue will not return undefined as value', () => {
const defaults = {bogusValue: 'hello'}
const value = getDefaultValue(
{defaultBogusValue: undefined},
'bogusValue',
defaults,
)

expect(value).toEqual(defaults.bogusValue)
})
})
19 changes: 11 additions & 8 deletions src/hooks/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -225,10 +225,10 @@ function getDefaultValue(
propKey,
defaultStateValues = dropdownDefaultStateValues,
) {
const defaultPropKey = `default${capitalizeString(propKey)}`
const defaultValue = props[`default${capitalizeString(propKey)}`]

if (defaultPropKey in props) {
return props[defaultPropKey]
if (defaultValue !== undefined) {
return defaultValue
}

return defaultStateValues[propKey]
Expand All @@ -239,15 +239,18 @@ function getInitialValue(
propKey,
defaultStateValues = dropdownDefaultStateValues,
) {
if (propKey in props) {
return props[propKey]
const value = props[propKey]

if (value !== undefined) {
return value
}

const initialPropKey = `initial${capitalizeString(propKey)}`
const initialValue = props[`initial${capitalizeString(propKey)}`]

if (initialPropKey in props) {
return props[initialPropKey]
if (initialValue !== undefined) {
return initialValue
}

return getDefaultValue(props, propKey, defaultStateValues)
}

Expand Down

0 comments on commit 1054249

Please sign in to comment.