add GlobalSearchContext
This commit is contained in:
parent
388dd2c992
commit
c7d729ae19
27
src/libs/GlobalSearchContext/Provider.tsx
Normal file
27
src/libs/GlobalSearchContext/Provider.tsx
Normal file
|
@ -0,0 +1,27 @@
|
|||
import React, { useState } from 'react';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import { SEARCH_PAGE } from '@config/routes';
|
||||
|
||||
import Context from './context';
|
||||
|
||||
export interface Props {
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
function Provider({ children }: Props) {
|
||||
const [q, setQ] = useState<string>('');
|
||||
const history = useHistory();
|
||||
const href = SEARCH_PAGE + `?q=${encodeURIComponent(q)}`;
|
||||
|
||||
const goToSearchPage = () => {
|
||||
history.push(href);
|
||||
};
|
||||
|
||||
return (
|
||||
<Context.Provider value={{ q, setQ, href, goToSearchPage }}>
|
||||
{children}
|
||||
</Context.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export default Provider;
|
11
src/libs/GlobalSearchContext/context.ts
Normal file
11
src/libs/GlobalSearchContext/context.ts
Normal file
|
@ -0,0 +1,11 @@
|
|||
import { createContext } from 'react';
|
||||
import { ContextValue } from './types';
|
||||
|
||||
const ctx = createContext<ContextValue>({
|
||||
href: '',
|
||||
q: '',
|
||||
setQ: (v: string) => {},
|
||||
goToSearchPage: () => {},
|
||||
});
|
||||
|
||||
export default ctx;
|
6
src/libs/GlobalSearchContext/types.ts
Normal file
6
src/libs/GlobalSearchContext/types.ts
Normal file
|
@ -0,0 +1,6 @@
|
|||
export type ContextValue = {
|
||||
href: string;
|
||||
q: string;
|
||||
setQ: (v: string) => void;
|
||||
goToSearchPage: () => void;
|
||||
};
|
9
src/libs/GlobalSearchContext/useGlobalSearch.ts
Normal file
9
src/libs/GlobalSearchContext/useGlobalSearch.ts
Normal file
|
@ -0,0 +1,9 @@
|
|||
import { useContext } from 'react';
|
||||
import ctx from './context';
|
||||
import { ContextValue } from './types';
|
||||
|
||||
const useGlobalSearch = (): ContextValue => {
|
||||
return useContext(ctx);
|
||||
};
|
||||
|
||||
export default useGlobalSearch;
|
Reference in New Issue
Block a user