@@ -5,9 +5,10 @@ import { api } from "./api";
5
5
import { EditmodeContext } from "./EditmodeContext" ;
6
6
import { renderChunk } from "./utils/renderChunk.jsx" ;
7
7
import { computeContentKey } from "./utils/computeContentKey" ;
8
+ import { Platform , AsyncStorage } from 'react-native' ;
8
9
9
10
export function useChunk ( defaultContent , { identifier, type } ) {
10
- const { projectId } = useContext ( EditmodeContext ) ;
11
+ const { projectId, defaultChunks } = useContext ( EditmodeContext ) ;
11
12
const [ [ error , chunk ] , setResponse ] = useState ( [ undefined , undefined ] ) ;
12
13
const contentKey = defaultContent ? computeContentKey ( defaultContent ) : null ;
13
14
const url = identifier
@@ -43,13 +44,61 @@ export function useChunk(defaultContent, { identifier, type }) {
43
44
} ;
44
45
}
45
46
47
+ const fallbackChunk = defaultChunks . filter ( chunkItem => chunkItem . identifier === identifier ) [ 0 ] ;
48
+
46
49
if ( ! chunk ) {
47
- return {
48
- Component ( ) {
49
- return null ;
50
- } ,
51
- content : defaultContent ,
52
- } ;
50
+ if ( ! defaultContent && ! fallbackChunk ) {
51
+ let cachedChunk ;
52
+
53
+ // Fetch Data
54
+ if ( Platform . OS === 'web' ) {
55
+ cachedChunk = localStorage . getItem ( identifier ) ;
56
+ } else {
57
+ const fetchChunk = async ( ) => {
58
+ try {
59
+ cachedChunk = await AsyncStorage . getItem ( identifier ) ;
60
+ } catch ( error ) {
61
+ console . log ( 'Error in fetching chunk.' , error ) ;
62
+ }
63
+ } ;
64
+ }
65
+ return {
66
+ Component ( ) {
67
+ return null ;
68
+ } ,
69
+ content : cachedChunk ,
70
+ } ;
71
+ } else if ( fallbackChunk ) {
72
+ return {
73
+ Component ( ) {
74
+ return null ;
75
+ } ,
76
+ content : fallbackChunk ,
77
+ } ;
78
+ } else if ( defaultContent ) {
79
+ return {
80
+ Component ( ) {
81
+ return null ;
82
+ } ,
83
+ content : defaultContent ,
84
+ } ;
85
+ }
86
+ } else {
87
+ // Store Data
88
+ if ( Platform . OS === 'web' ) {
89
+ localStorage . setItem ( chunk . identifier , JSON . stringify ( chunk ) ) ;
90
+ } else {
91
+ const storeChunk = async ( ) => {
92
+ try {
93
+ await AsyncStorage . setItem (
94
+ chunk . identifier ,
95
+ JSON . stringify ( chunk )
96
+ ) ;
97
+ } catch ( error ) {
98
+ console . log ( 'Error in saving chunk.' , error ) ;
99
+ }
100
+ }
101
+ }
53
102
}
54
103
55
104
return {
0 commit comments