Skip to content

Commit

Permalink
Add equip persistence
Browse files Browse the repository at this point in the history
  • Loading branch information
tiliv committed Apr 26, 2024
1 parent 64e970f commit c1937ac
Showing 1 changed file with 22 additions and 7 deletions.
29 changes: 22 additions & 7 deletions src/hooks/useInventory.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,20 @@ function setInventoryType(subject, kind, items) {
localStorage.setItem(key, itemsString);
}

export default function useInventory(subject) {
function getEquipmentType(subject, kind) {
const saveSlot = localStorage.getItem('latest');
const key = `${saveSlot}/${subject}/equipped/${kind}`;
const id = localStorage.getItem(key);
return parseInt(id, 10) || null;
};

function setEquipmentType(subject, kind, id) {
const saveSlot = localStorage.getItem('latest');
const key = `${saveSlot}/${subject}/inventory`;
const key = `${saveSlot}/${subject}/equipped/${kind}`;
localStorage.setItem(key, id);
};

export default function useInventory(subject) {
const [inventory, setInventory] = useState({});
const [equipment, setEquipment] = useState({});

Expand All @@ -50,18 +60,23 @@ export default function useInventory(subject) {
const equipment = Object.fromEntries(CATEGORIES.map((category) => [category, null]));
CATEGORIES.forEach((kind) => {
const items = getInventoryType(subject, kind);
const equipped = getEquipmentType(subject, kind);
inventory[kind].push(...items);
equipment[kind] = inventory[kind].find(({ equipped }) => equipped)?.id || null;
equipment[kind] = inventory[kind].find(({ id }) => id === equipped)?.id || null;
});
setInventory(inventory);
setEquipment(equipment);
}, [subject]);

const equip = function(kind, id) {
setEquipment((equipment) => ({
...equipment,
[kind]: id,
}));
setEquipment((equipment) => {
const newEquipment = {
...equipment,
[kind]: id,
};
setEquipmentType(subject, kind, newEquipment[kind]);
return newEquipment;
});
};

const acquire = function(kind, item) {
Expand Down

0 comments on commit c1937ac

Please sign in to comment.