Get items from localStorage and export them
I have a function where it takes fields stored in state and returns them if they exist.
export const hasNameAndTokenSelector = (state) => {
const { fields } = baseInputsSelector(state);
const hasName = !isNil(prop('name')(fields));
const hasToken = !isNil(prop('token')(fields));
return hasName && hasToken;
};
But now I need to use this same function to get items stored in localStorage. I'm trying to do the following:
export const hasNameAndTokenSelector = (state) => {
if (localStorage.getItem('inputs') !== null) {
const localInputs = JSON.parse(localStorage.getItem('inputs'));
const hasToken = localInputs[0].token;
const hasName = localInputs[0].name;
return hasName && hasToken;
}
};
The format of localInputs is:
{
"name":"John Doe",
"token":"string123-9882",
}
But it doesn't work, I believe it's because I need the state parameter and the return is inside an if, but I don't know the correct way to proceed.
How should I get these stored items and return them? I need to use hasNameAndTokenSelector in another file.
Thanks!!
From the above comment ...
"... code review ... since the function's name is
hasNameAndTokenSelector
it is expected to always return a boolean value, neither once [theundefined
default], nor either of the string valueslocalInputs.token
/localInputs.name
."
Thus, in order to solve the OP's original problem ...
"How should I get these stored items and return them?"
... the OP's provided approach might be best refactored into two functions, one which fulfills the getNameAndToken
part and another one which covers the already existing hasNameAndToken
part ...
// `storedInputs` structure ...
// {
// "name":"John Doe",
// "token":"string123-9882",
// }
export const getNameAndToken = () => {
const storedInputs = localStorage.getItem('inputs');
return (storedInputs !== null)
&& JSON.parse(storedInputs)
|| {};
};
export const hasNameAndToken = () => {
const { name, token } = getNameAndToken();
return !!(name && token);
};
// usage in other modules
import { getNameAndToken/*, hasNameAndToken*/ } from '/'
const { name, token } = getNameAndToken();