-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhooks.js
32 lines (27 loc) · 814 Bytes
/
hooks.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { useState, useEffect } from "react";
import { generate } from "shortid";
import { AsyncStorage } from "react-native";
export const useColors = () => {
const [colors, setColors] = useState([]);
const loadColors = async () => {
const colorData = await AsyncStorage.getItem("@ColorListStore:Colors");
if (colorData) {
const colors = JSON.parse(colorData);
setColors(colors);
}
};
// load initial color data
useEffect(() => {
if (colors.length) return;
loadColors();
}, []);
// save colors
useEffect(() => {
AsyncStorage.setItem("@ColorListStore:Colors", JSON.stringify(colors));
}, [colors]);
const addColor = (color) => {
const newColor = { id: generate(), color };
setColors([newColor, ...colors]);
};
return { colors, addColor };
};