Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

formatString returns "TypeError: Cannot read property '0' of undefined" #186

Open
zhenghow93 opened this issue Apr 10, 2020 · 2 comments
Open

Comments

@zhenghow93
Copy link

zhenghow93 commented Apr 10, 2020

I have upgraded from version 0.1.32 to version 2.1.6, and formatString is broken.
react-native version 0.61.5

For example:

strings: {
   info: 'Bread will be done in {0} minutes.'
}
const minute = 30;

Previously I could use it like strings.formatString(strings.info, minute) and it will display Bread will be done in 30 minutes..
Now it gives error TypeError: Cannot read property '0' of undefined.

After some experiments, I realised that strings.formatString(strings.info, [30]) would work.
The README did not mention that we have to enclose the string params with [] square brackets.

Anything that I have missed?
Thanks in advance.

@zhenghow93
Copy link
Author

zhenghow93 commented Apr 10, 2020

Ah, okay. I realised that the minute was undefined at first, and then only updated with a value afterwards.
Previous version will fill it with undefined for a while then update the value after it's updated.
Any ways to accommodate undefined value?

@jerearaujo03
Copy link

I made a function to protect agains this error

export const formatString = (key, ...values) => {
  const variables = values?.map(val => val || '');
  return strings.formatString(key, ...variables);
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants