I am trying to setPackages in useEffect everything is working fine except setPackages method. It do not work first time but when I refresh app by saving CTRL+S from VS Code it works and setPackages works.
Following is the code.
const [packages, setPackages] = useState([]);
useEffect(() => {
const getPackages = async () => {
Purchases.setDebugLogsEnabled(true);
Purchases.setup("MY_KEY_HERE");
try {
const offerings = await Purchases.getOfferings();
if (offerings.current !== null) {
console.log(offerings.current.availablePackages); //This displays the data (works)
setPackages(offerings.current.availablePackages); //This do not set the data in packages unless app refreshed
}else{
console.log("No offerings found");
}
} catch (e) {
console.log("Error => " + e);
}
}
getPackages();
},[])
I need to refresh app every time to make this line work. What could be issue here?
You are declaring the function, but not calling it. And you should include an empty deps array in useEffect if you want this to be call once on start and not over and over again.
const [packages, setPackages] = useState([]);
useEffect(() => {
const getPackages = async () => {
Purchases.setDebugLogsEnabled(true);
Purchases.setup("MY_KEY_HERE");
try {
const offerings = await Purchases.getOfferings();
if (offerings.current !== null) {
console.log(offerings.current.availablePackages); //This displays the data (works)
setPackages(offerings.current.availablePackages); //This do not set the data in packages unless app refreshed
}else{
console.log("No offerings found");
}
} catch (e) {
console.log("Error => " + e);
}
};
getPackages();
},[])
May I suggest this hook to handle your packages-state?
Use it like this:
function MyComponent() {
// Load packages (will be undefined while loading or updating)
const packages = usePromiseMemo(() => {
Purchases.setDebugLogsEnabled(true);
Purchases.setup('MY_KEY_HERE');
return Purchases.getOfferings().then(offerings => {
if (offerings.current) {
console.log(offerings.current.availablePackages); //This displays the data (works)
return offerings.current.availablePackages;
} else {
console.log('No offerings found');
}
return undefined;
});
}, []); // Alternatively: Replace [] with [Purchases]
// Render
return <div>More stuff here</div>;
}
I don't know where Purchases comes from, but add it to the dependency array if it is subject to change.
Also, if 'MY_KEY_HERE' is stored in some variable, add that to the dependency array too.