(
subject: string,
opts: {
/**
* If this is true, incomplete resources will not be automatically fetched.
* This limits the amount of requests. Use this for things like menu items.
*/
allowIncomplete?: boolean;
/**
* Set to true if you are initializing a new resource. The resource will not
* be fetched.
*/
newResource?: boolean;
} = { allowIncomplete: false, newResource: false },
)
| 22 | * subject and add its parsed values to the store. |
| 23 | */ |
| 24 | export function useResource( |
| 25 | subject: string, |
| 26 | opts: { |
| 27 | /** |
| 28 | * If this is true, incomplete resources will not be automatically fetched. |
| 29 | * This limits the amount of requests. Use this for things like menu items. |
| 30 | */ |
| 31 | allowIncomplete?: boolean; |
| 32 | /** |
| 33 | * Set to true if you are initializing a new resource. The resource will not |
| 34 | * be fetched. |
| 35 | */ |
| 36 | newResource?: boolean; |
| 37 | } = { allowIncomplete: false, newResource: false }, |
| 38 | ): Resource { |
| 39 | const { newResource, allowIncomplete } = opts; |
| 40 | const store = useStore(); |
| 41 | const [resource, setResource] = useState<Resource>( |
| 42 | store.getResourceLoading(subject, { |
| 43 | newResource, |
| 44 | allowIncomplete, |
| 45 | }), |
| 46 | ); |
| 47 | |
| 48 | // If the subject changes, make sure to change the resource! |
| 49 | useEffect(() => { |
| 50 | setResource( |
| 51 | store.getResourceLoading(subject, { |
| 52 | newResource, |
| 53 | allowIncomplete, |
| 54 | }), |
| 55 | ); |
| 56 | }, [subject, store]); |
| 57 | |
| 58 | // When a component mounts, it needs to let the store know that it will subscribe to changes to that resource. |
| 59 | useEffect(() => { |
| 60 | function handleNotify(updated: Resource) { |
| 61 | // When a change happens, set the new Resource. |
| 62 | setResource(updated); |
| 63 | } |
| 64 | subject && store.subscribe(subject, handleNotify); |
| 65 | |
| 66 | return () => { |
| 67 | // When the component is unmounted, unsubscribe from the store. |
| 68 | store.unsubscribe(subject, handleNotify); |
| 69 | }; |
| 70 | }, [store, subject]); |
| 71 | |
| 72 | return resource; |
| 73 | } |
| 74 | |
| 75 | /** |
| 76 | * Converts an array of Atomic URL strings to an array of Resources. Could take |
no test coverage detected