Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Fix getIn unexpected value #3237

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/kind-poems-kick.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'formik': patch
---

Changed `getIn` to return undefined when it can't find a value AND a parent of that value is "falsy" ( "" / 0 / null / false )
6 changes: 6 additions & 0 deletions packages/formik/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,12 @@ export function getIn(
while (obj && p < path.length) {
obj = obj[path[p++]];
}

// check if path is not in the end
if (p !== path.length && !obj) {
return def;
}

return obj === undefined ? def : obj;
}

Expand Down
20 changes: 20 additions & 0 deletions packages/formik/test/utils.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,11 @@ describe('utils', () => {
const obj = {
a: {
b: 2,
c: false,
d: null,
},
t: true,
s: 'a random string',
};

it('gets a value by array path', () => {
Expand All @@ -166,6 +170,22 @@ describe('utils', () => {
it('return "undefined" if value was not found using given path', () => {
expect(getIn(obj, 'a.z')).toBeUndefined();
});

it('return "undefined" if value was not found using given path and an intermediate value is "false"', () => {
expect(getIn(obj, 'a.c.z')).toBeUndefined();
});

it('return "undefined" if value was not found using given path and an intermediate value is "null"', () => {
expect(getIn(obj, 'a.d.z')).toBeUndefined();
});

it('return "undefined" if value was not found using given path and an intermediate value is "true"', () => {
expect(getIn(obj, 't.z')).toBeUndefined();
});

it('return "undefined" if value was not found using given path and an intermediate value is a string', () => {
expect(getIn(obj, 's.z')).toBeUndefined();
});
});

describe('setIn', () => {
Expand Down