Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix/fine-tune react-query settings #389

Merged
merged 19 commits into from
Apr 29, 2021
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions src/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ const BACKEND_URL = process.env.REACT_APP_BACKEND_URL

const getDirectoryFile = async (siteName, folderName) => {
if (!folderName) return
return await axios.get(`${BACKEND_URL}/sites/${siteName}/collections/${folderName}/pages/collection.yml`);
const resp = await axios.get(`${BACKEND_URL}/sites/${siteName}/collections/${folderName}/pages/collection.yml`);
return resp.data
}

const setDirectoryFile = async (siteName, folderName, payload) => {
Expand Down Expand Up @@ -80,7 +81,8 @@ const getEditPageData = async ({folderName, subfolderName, fileName, siteName, r

const getCsp = async (siteName) => {
// retrieve CSP
return await axios.get(`${process.env.REACT_APP_BACKEND_URL}/sites/${siteName}/netlify-toml`);
const resp = await axios.get(`${process.env.REACT_APP_BACKEND_URL}/sites/${siteName}/netlify-toml`)
return resp.data
}

const createPageData = async ({folderName, subfolderName, newFileName, siteName, resourceName}, content) => {
Expand Down Expand Up @@ -161,7 +163,9 @@ const getAllCategories = async ({siteName, isResource}) => {
}

const getAllResourceCategories = async (siteName) => {
return await axios.get(`${BACKEND_URL}/sites/${siteName}/resources`);
const apiEndpoint = `${BACKEND_URL}/sites/${siteName}/resources`
const resp = await axios.get(apiEndpoint)
return resp.data;
}

const addResourceCategory = async (siteName, resourceName) => {
Expand All @@ -177,7 +181,9 @@ const getPages = async ({ siteName }) => {

const getResourcePages = async (siteName, resourceName) => {
if (!resourceName) return
return await axios.get(`${BACKEND_URL}/sites/${siteName}/resources/${resourceName}`);
const apiEndpoint = `${BACKEND_URL}/sites/${siteName}/resources/${resourceName}`
const resp = await axios.get(apiEndpoint)
return resp.data;
}

// EditNavBar
Expand Down
21 changes: 14 additions & 7 deletions src/components/CollectionPagesSection.jsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import React, { useState } from 'react';
import axios from 'axios';
import { useQuery, useMutation } from 'react-query';
import { useQuery, useMutation, useQueryClient } from 'react-query';
import PropTypes from 'prop-types';
import _ from 'lodash';

import {
PAGE_CONTENT_KEY,
FOLDERS_CONTENT_KEY,
DIR_CONTENT_KEY,
RESOURCE_CATEGORY_CONTENT_KEY,
} from '../constants'

import { getEditPageData, deletePageData, getAllCategories, moveFile, getDirectoryFile } from '../api'
Expand All @@ -31,8 +32,8 @@ import contentStyles from '../styles/isomer-cms/pages/Content.module.scss';
axios.defaults.withCredentials = true

// Clean up note: Should be renamed, only used for resource pages and unlinked pages sections
const CollectionPagesSection = ({ collectionName, pages, siteName, isResource, refetchPages }) => {

const CollectionPagesSection = ({ collectionName, pages, siteName, isResource }) => {
const queryClient = useQueryClient()
const initialMoveDropdownQueryState = {
folderName: '',
subfolderName: '',
Expand Down Expand Up @@ -95,7 +96,7 @@ const CollectionPagesSection = ({ collectionName, pages, siteName, isResource, r
return []
}
if (folderName !== '' && querySubfolders) { // inside folder, show all subfolders
const { order: parsedFolderContents } = parseDirectoryFile(querySubfolders.data.content)
const { order: parsedFolderContents } = parseDirectoryFile(querySubfolders.content)
const parsedFolderArray = convertFolderOrderToArray(parsedFolderContents)
return parsedFolderArray.filter(file => file.type === 'dir').map(file => file.fileName)
}
Expand All @@ -114,7 +115,12 @@ const CollectionPagesSection = ({ collectionName, pages, siteName, isResource, r
async () => await deletePageData({ siteName, fileName: selectedFile, resourceName: collectionName }, pageData.pageSha),
{
onError: () => errorToast(`Your file could not be deleted successfully. ${DEFAULT_RETRY_MSG}`),
onSuccess: () => {successToast('Successfully deleted file'); refetchPages();},
onSuccess: () => {
setSelectedFile('')
if (isResource) queryClient.invalidateQueries([RESOURCE_CATEGORY_CONTENT_KEY, siteName, collectionName, true])
else queryClient.invalidateQueries([PAGE_CONTENT_KEY, { siteName }])
successToast('Successfully deleted file')
},
onSettled: () => setCanShowDeleteWarningModal((prevState) => !prevState),
}
)
Expand All @@ -128,8 +134,10 @@ const CollectionPagesSection = ({ collectionName, pages, siteName, isResource, r
onError: () => errorToast(`Your file could not be moved successfully. ${DEFAULT_RETRY_MSG}`),
onSuccess: (samePage) => {
if (samePage) return successToast('Page is already in this folder')
setSelectedFile('')
if (isResource) queryClient.invalidateQueries([RESOURCE_CATEGORY_CONTENT_KEY, siteName, collectionName, true])
else queryClient.invalidateQueries([PAGE_CONTENT_KEY, { siteName }])
successToast('Successfully moved file')
refetchPages()
},
onSettled: () => setCanShowMoveModal(prevState => !prevState),
}
Expand Down Expand Up @@ -246,5 +254,4 @@ CollectionPagesSection.propTypes = {
),
siteName: PropTypes.string.isRequired,
isResource: PropTypes.bool,
refetchPages: PropTypes.func.isRequired,
};
18 changes: 11 additions & 7 deletions src/components/ComponentSettingsModal.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useState, useEffect } from 'react';
import { useMutation } from 'react-query';
import { useMutation, useQueryClient } from 'react-query';
import axios from 'axios';
import PropTypes from 'prop-types';
import * as _ from 'lodash';
Expand All @@ -8,6 +8,7 @@ import FormField from './FormField';
import FormFieldHorizontal from './FormFieldHorizontal';
import ResourceFormFields from './ResourceFormFields';
import SaveDeleteButtons from './SaveDeleteButtons';
import { RESOURCE_CATEGORY_CONTENT_KEY } from '../constants'

import useSiteUrlHook from '../hooks/useSiteUrlHook';
import useRedirectHook from '../hooks/useRedirectHook';
Expand All @@ -24,7 +25,7 @@ import {
import { createPageData, updatePageData, renamePageData } from '../api'

import { validateResourceSettings } from '../utils/validators';
import { errorToast } from '../utils/toasts';
import { errorToast, successToast } from '../utils/toasts';

import elementStyles from '../styles/isomer-cms/Elements.module.scss';

Expand All @@ -41,6 +42,9 @@ const ComponentSettingsModal = ({
setSelectedFile,
setIsComponentSettingsActive,
}) => {
// Instantiate queryClient
const queryClient = useQueryClient()

const { setRedirectToPage } = useRedirectHook()
const { retrieveSiteUrl } = useSiteUrlHook()

Expand All @@ -54,7 +58,6 @@ const ComponentSettingsModal = ({
const [hasErrors, setHasErrors] = useState(false)

// Base hooks
const [baseApiUrl, setBaseApiUrl] = useState('');
const [title, setTitle] = useState('')
const [permalink, setPermalink] = useState('')
const [mdBody, setMdBody] = useState('')
Expand All @@ -72,9 +75,6 @@ const ComponentSettingsModal = ({

const [siteUrl, setSiteUrl] = useState('https://abc.com.sg')

// Page redirection modals
const [canShowDeleteWarningModal, setCanShowDeleteWarningModal] = useState(false)

// Map element ID to setter functions
const idToSetterFuncMap = {
title: setTitle,
Expand Down Expand Up @@ -176,7 +176,11 @@ const ComponentSettingsModal = ({
},
{
onSettled: () => {setSelectedFile(''); setIsComponentSettingsActive(false)},
onSuccess: (redirectUrl) => redirectUrl && isPost ? setRedirectToPage(redirectUrl) : window.location.reload(),
onSuccess: (redirectUrl) => {
queryClient.invalidateQueries([RESOURCE_CATEGORY_CONTENT_KEY, siteName, category, true])
if (redirectUrl && isPost) setRedirectToPage(redirectUrl)
else successToast(`Successfully updated file settings!`)
},
onError: () => errorToast(`${isNewFile ? 'A new resource page could not be created.' : 'Your resource page settings could not be saved.'} ${DEFAULT_RETRY_MSG}`)
}
)
Expand Down
22 changes: 19 additions & 3 deletions src/components/FolderModal.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { useState } from 'react';
import axios from 'axios';
import PropTypes from 'prop-types';
import { useMutation } from 'react-query';
import { useMutation, useQueryClient } from 'react-query';
import elementStyles from '../styles/isomer-cms/Elements.module.scss';
import SaveDeleteButtons from './SaveDeleteButtons';
import FormField from './FormField';
Expand All @@ -19,7 +19,8 @@ import {
} from '../utils'

import { validateCategoryName } from '../utils/validators'
import { errorToast } from '../utils/toasts';
import { errorToast, successToast } from '../utils/toasts';
import { DIR_CONTENT_KEY, FOLDERS_CONTENT_KEY, RESOURCE_ROOM_CONTENT_KEY } from '../constants';

// axios settings
axios.defaults.withCredentials = true
Expand Down Expand Up @@ -54,6 +55,8 @@ const selectRenameApiCall = (isCollection, siteName, folderOrCategoryName, subfo
}

const FolderModal = ({ displayTitle, displayText, onClose, folderOrCategoryName, subfolderName, siteName, isCollection, existingFolders }) => {
// Instantiate queryClient
const queryClient = useQueryClient()
const [newDirectoryName, setNewDirectoryName] = useState(deslugifyDirectory(subfolderName || folderOrCategoryName))
const [errors, setErrors] = useState('')

Expand All @@ -62,7 +65,20 @@ const FolderModal = ({ displayTitle, displayText, onClose, folderOrCategoryName,
() => selectRenameApiCall(isCollection, siteName, folderOrCategoryName, subfolderName, newDirectoryName),
{
onError: () => errorToast(`There was a problem trying to rename this folder. ${DEFAULT_RETRY_MSG}`),
onSuccess: () => window.location.reload(),
onSuccess: () => {
if (!isCollection) {
// Resource folder
console.log('hey')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to remove

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

queryClient.invalidateQueries([RESOURCE_ROOM_CONTENT_KEY, siteName])
} else if (subfolderName) {
// Collection subfolder
queryClient.invalidateQueries([DIR_CONTENT_KEY, siteName, folderOrCategoryName, undefined])
} else {
queryClient.invalidateQueries([FOLDERS_CONTENT_KEY, { siteName, isResource: false }])
}
onClose()
successToast(`Successfully renamed folder!`)
},
},
)

Expand Down
26 changes: 19 additions & 7 deletions src/components/PageSettingsModal.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useState, useEffect } from 'react';
import { useMutation } from 'react-query';
import PropTypes from 'prop-types';
import { useMutation, useQueryClient } from 'react-query';
import axios from 'axios';
import * as _ from 'lodash';

Expand All @@ -14,11 +14,12 @@ import {
} from '../utils';

import { createPageData, updatePageData, renamePageData } from '../api'
import { PAGE_SETTINGS_KEY, DIR_CONTENT_KEY, PAGE_CONTENT_KEY } from '../constants'

import elementStyles from '../styles/isomer-cms/Elements.module.scss';

import { validatePageSettings } from '../utils/validators';
import { errorToast } from '../utils/toasts';
import { errorToast, successToast } from '../utils/toasts';

import FormField from './FormField';
import FormFieldHorizontal from './FormFieldHorizontal';
Expand All @@ -41,6 +42,9 @@ const PageSettingsModal = ({
setSelectedPage,
setIsPageSettingsActive,
}) => {
// Instantiate queryClient
const queryClient = useQueryClient()

// Errors
const [errors, setErrors] = useState({
title: '',
Expand All @@ -56,9 +60,7 @@ const PageSettingsModal = ({
const [originalFrontMatter, setOriginalFrontMatter] = useState({})
const [sha, setSha] = useState('')
const [mdBody, setMdBody] = useState('')

const [siteUrl, setSiteUrl] = useState('https://abc.com.sg')

const { setRedirectToPage } = useRedirectHook()
const { retrieveSiteUrl } = useSiteUrlHook()

Expand All @@ -79,7 +81,15 @@ const PageSettingsModal = ({
},
{
onSettled: () => {setSelectedPage(''); setIsPageSettingsActive(false)},
onSuccess: (redirectUrl) => redirectUrl ? setRedirectToPage(redirectUrl) : window.location.reload(),
onSuccess: (redirectUrl) => {
queryClient.invalidateQueries([PAGE_SETTINGS_KEY, originalPageName])
if (redirectUrl) setRedirectToPage(redirectUrl)
else {
if (folderName) queryClient.invalidateQueries([DIR_CONTENT_KEY, siteName, folderName, subfolderName])
else queryClient.invalidateQueries([PAGE_CONTENT_KEY, { siteName }])
successToast(`Successfully updated page settings!`)
}
},
onError: () => errorToast(`${isNewPage ? 'A new page could not be created.' : 'Your page settings could not be saved.'} ${DEFAULT_RETRY_MSG}`)
}
)
Expand Down Expand Up @@ -134,8 +144,10 @@ const PageSettingsModal = ({
}, [errors])

useEffect(() => {
setHasChanges(!isNewPage && !(originalPageName === generatePageFileName(title) && originalPermalink === permalink))
}, [title, permalink])
if (title && permalink) {
setHasChanges(!isNewPage && !(title === deslugifyPage(originalPageName) && permalink === originalPermalink))
}
}, [originalPageName, originalPermalink, title, permalink])

const changeHandler = (event) => {
const { id, value } = event.target;
Expand Down
1 change: 1 addition & 0 deletions src/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ export const RESOURCE_CATEGORY_CONTENT_KEY = 'resource-category-contents'
export const RESOURCE_ROOM_CONTENT_KEY = 'resource-room-contents'
export const FOLDERS_CONTENT_KEY = 'folders-contents'
export const LAST_UPDATED_KEY = 'last-updated'
export const PAGE_SETTINGS_KEY = 'page-settings';
5 changes: 2 additions & 3 deletions src/layouts/CategoryPages.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ const CategoryPages = ({ match, location, isResource }) => {

const [categoryPages, setCategoryPages] = useState()

const { data: resourcePagesResp, refetch: refetchPages } = useQuery(
const { data: resourcePagesResp } = useQuery(
[RESOURCE_CATEGORY_CONTENT_KEY, siteName, collectionName, isResource],
() => getResourcePages(siteName, collectionName),
{
Expand All @@ -64,7 +64,7 @@ const CategoryPages = ({ match, location, isResource }) => {
const fetchData = async () => {
if (isResource) {
if (!resourcePagesResp) return
const { resourcePages } = resourcePagesResp.data;
const { resourcePages } = resourcePagesResp;

if (resourcePages.length > 0) {
const retrievedResourcePages = resourcePages.map((resourcePage) => {
Expand Down Expand Up @@ -123,7 +123,6 @@ const CategoryPages = ({ match, location, isResource }) => {
pages={categoryPages}
siteName={siteName}
isResource={isResource}
refetchPages={refetchPages}
/>
</div>
{/* main section ends here */}
Expand Down
Loading