-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathcontext.js
More file actions
59 lines (48 loc) · 1.74 KB
/
Copy pathcontext.js
File metadata and controls
59 lines (48 loc) · 1.74 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import React, { useContext, useMemo } from "react";
import { ApplicationsContext } from "../application";
import { useMlpApi } from "../../hooks/useMlpApi";
import { useMatch } from "react-router-dom";
import urlJoin from "proper-url-join";
const projectIdKey = "lastSelectedProjectId";
const isInt = str => !isNaN(parseInt(str));
const getSelectedProjectId = (projectId, projects) => {
// If projectId is not a valid ID, read last selected projectId from the local storage
if (!isInt(projectId)) {
projectId = localStorage.getItem(projectIdKey);
// If local storage doesn't contain valid projectId, sort projects alphabetically
// and select ID of the first project from the list
if (!isInt(projectId)) {
projectId = projects.sort((a, b) => a.name.localeCompare(b.name))?.[0]
?.id;
}
}
localStorage.setItem(projectIdKey, projectId);
return projectId;
};
const Context = React.createContext({
projects: [],
currentProject: undefined,
refresh: () => {}
});
export const ProjectsContextProvider = ({ children }) => {
const [{ data: projects }, refresh] = useMlpApi(`/v1/projects`, {}, []);
const { currentApp = {} } = useContext(ApplicationsContext);
const projectIdMatch = useMatch({
path: urlJoin(currentApp.homepage, "/projects/:projectId"),
caseSensitive: true,
end: false
});
const currentProject = useMemo(() => {
const selectedProjectId = getSelectedProjectId(
projectIdMatch?.params?.projectId,
projects
);
return (projects || []).find(p => String(p.id) === selectedProjectId);
}, [projects, projectIdMatch]);
return (
<Context.Provider value={{ projects, currentProject, refresh }}>
{children}
</Context.Provider>
);
};
export default Context;