diff --git a/components/reuse/Search.js b/components/reuse/Search.js index 9eae2e2..7d44036 100644 --- a/components/reuse/Search.js +++ b/components/reuse/Search.js @@ -1,8 +1,10 @@ -import React, { useState } from 'react'; +import React, { useContext, useState } from 'react'; import { FaSearch, FaSpinner } from 'react-icons/fa'; import { useRouter } from 'next/router'; +import { AppContext } from '../../pages/_app'; const Search = ({ height }) => { + const { isLoading, toggleLoading } = useContext(AppContext) const router = useRouter(); const [loading, setLoading] = useState(false); @@ -15,12 +17,13 @@ const Search = ({ height }) => { if (username && !hasWhiteSpaceText(username)) { setLoading(true); + toggleLoading(true) router.push(`/user/${username}`); } }; const hasWhiteSpaceText = (text) => { - return /\s/g.test(text); + return /\s/g.test(text); }; return ( @@ -39,7 +42,7 @@ const Search = ({ height }) => { type="submit" className="bg-purple-mid text-white h-full px-4 rounded-r-md" > - {loading ? ( + {isLoading ? (
diff --git a/pages/_app.js b/pages/_app.js index cfc4867..862c566 100644 --- a/pages/_app.js +++ b/pages/_app.js @@ -1,3 +1,4 @@ +import React, { useReducer } from 'react'; import { ThemeProvider } from 'next-themes'; import { RecoilRoot } from 'recoil'; import '../styles/globals.css'; @@ -12,19 +13,40 @@ import { ApolloProvider } from '@apollo/client'; import { client } from '../client'; import Footer from '../components/footer/Footer'; +export const AppContext = React.createContext(); + +const reducer = (state, action) => { + if (action.type === 'LOADING_TOGGLE') { + return { ...state, isLoading: action.payload }; + } + return state; +}; +const initialStates = { isLoading: false } function MyApp({ Component, pageProps }) { + + const [state, dispatch] = useReducer(reducer, initialStates) + + const toggleLoading = async (flag) => { + dispatch({ + type: 'LOADING_TOGGLE', + payload: flag + }); + } + return ( - - -