(
fetch: Input => Thenable<Value>,
hashInput: Input => Key,
config?: Config = {},
)
| 121 | } |
| 122 | |
| 123 | export function createResource<Input, Key, Value>( |
| 124 | fetch: Input => Thenable<Value>, |
| 125 | hashInput: Input => Key, |
| 126 | config?: Config = {}, |
| 127 | ): Resource<Input, Key, Value> { |
| 128 | const resource = { |
| 129 | clear(): void { |
| 130 | entries.delete(resource); |
| 131 | }, |
| 132 | |
| 133 | invalidate(key: Key): void { |
| 134 | const entriesForResource = getEntriesForResource(resource); |
| 135 | entriesForResource.delete(key); |
| 136 | }, |
| 137 | |
| 138 | read(input: Input): Value { |
| 139 | // Prevent access outside of render. |
| 140 | readContext(CacheContext); |
| 141 | |
| 142 | const key = hashInput(input); |
| 143 | const result: Thenable<Value> = accessResult(resource, fetch, input, key); |
| 144 | if (typeof React.use === 'function') { |
| 145 | // eslint-disable-next-line react-hooks-published/rules-of-hooks |
| 146 | return React.use(result); |
| 147 | } |
| 148 | |
| 149 | switch (result.status) { |
| 150 | case 'fulfilled': { |
| 151 | const value = result.value; |
| 152 | return value; |
| 153 | } |
| 154 | case 'rejected': { |
| 155 | const error = result.reason; |
| 156 | throw error; |
| 157 | } |
| 158 | default: |
| 159 | throw result; |
| 160 | } |
| 161 | }, |
| 162 | |
| 163 | preload(input: Input): void { |
| 164 | // Prevent access outside of render. |
| 165 | readContext(CacheContext); |
| 166 | |
| 167 | const key = hashInput(input); |
| 168 | accessResult(resource, fetch, input, key); |
| 169 | }, |
| 170 | |
| 171 | write(key: Key, value: Value): void { |
| 172 | const entriesForResource = getEntriesForResource(resource); |
| 173 | |
| 174 | const fulfilledThenable: FulfilledThenable<Value> = (Promise.resolve( |
| 175 | value, |
| 176 | ): any); |
| 177 | fulfilledThenable.status = 'fulfilled'; |
| 178 | fulfilledThenable.value = value; |
| 179 | |
| 180 | entriesForResource.set(key, fulfilledThenable); |
no test coverage detected