Skip to content

Commit

Permalink
Merge pull request #857 from stakwork/feature/update-useSocket
Browse files Browse the repository at this point in the history
feat: update websocket
  • Loading branch information
Rassl authored Feb 2, 2024
2 parents cfdbb48 + 76a9b10 commit 5ddd899
Show file tree
Hide file tree
Showing 8 changed files with 84 additions and 59 deletions.
17 changes: 7 additions & 10 deletions src/components/App/Helper/AskQuestion/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { TextareaAutosize } from '@mui/base'
import { FormControl, InputLabel, MenuItem, OutlinedInput, Select, SelectChangeEvent } from '@mui/material'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useCallback, useEffect, useState } from 'react'
import { MdSend } from 'react-icons/md'
import { PropagateLoader } from 'react-spinners'
import { toast } from 'react-toastify'
Expand All @@ -10,7 +10,7 @@ import styled from 'styled-components'
import { Flex } from '~/components/common/Flex'
import { Text } from '~/components/common/Text'
import { ToastMessage } from '~/components/common/Toast/toastMessage'
import useSocket from '~/hooks/useSockets'
import { useSocket } from '~/hooks/useSockets'
import { postAskQuestion } from '~/network/fetchGraphData'
import { useAppStore } from '~/stores/useAppStore'
import { useDataStore } from '~/stores/useDataStore'
Expand Down Expand Up @@ -42,8 +42,9 @@ export const AskQuestion = () => {
const [question, setQuestion] = useState('')
const [selectedValue, setSelectedValue] = useState<string>('Beginner')
const searchTerm = useAppStore((s) => s.currentSearch)
const isSocketSet: { current: boolean } = useRef<boolean>(false)
const socket: Socket | null = useSocket()

const socket: Socket | undefined = useSocket()

const [setBudget] = useUserStore((s) => [s.setBudget])

const [askedQuestions, askedQuestionsAnswers, setAskedQuestion, setAskedQuestionAnswer, hasQuestionInProgress] =
Expand All @@ -68,16 +69,12 @@ export const AskQuestion = () => {
)

useEffect(() => {
if (isSocketSet.current) {
if (!socket) {
return
}

if (handleAskQuestion) {
if (socket) {
socket.on('askquestionhook', handleAskQuestion)

isSocketSet.current = true
}
socket.on('askquestionhook', handleAskQuestion)
}
}, [handleAskQuestion, socket])

Expand Down
18 changes: 6 additions & 12 deletions src/components/App/Helper/TeachMe/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import styled from 'styled-components'
import { Flex } from '~/components/common/Flex'
import { Text } from '~/components/common/Text'
import { ToastMessage } from '~/components/common/Toast/toastMessage'
import useSocket from '~/hooks/useSockets'
import { postInstagraph, postTeachMe } from '~/network/fetchGraphData'
import { useAppStore } from '~/stores/useAppStore'
import { useDataStore } from '~/stores/useDataStore'
Expand All @@ -20,6 +19,7 @@ import { updateBudget } from '~/utils/setBudget'
import { AskQuestion } from '../AskQuestion'

import 'reactflow/dist/style.css'
import { useSocket } from '~/hooks/useSockets'

type ResponseType = {
tutorial: string
Expand All @@ -31,7 +31,7 @@ export const TeachMe = () => {
const [setBudget] = useUserStore((s) => [s.setBudget])

const isSocketSet: { current: boolean } = useRef<boolean>(false)
const socket: Socket | null = useSocket()
const socket: Socket | undefined = useSocket()

const [setTeachMeAnswer, setHasTeachingInProgress, setInstagraphAnswer, setHasInstagraphInProgress] = useTeachStore(
(s) => [s.setTeachMeAnswer, s.setHasTeachingInProgress, s.setInstagraphAnswer, s.setHasInstagraphInProgress],
Expand Down Expand Up @@ -62,24 +62,18 @@ export const TeachMe = () => {
)

useEffect(() => {
if (isSocketSet.current) {
if (!socket) {
return
}

if (handleTeachMe) {
if (socket) {
socket.on('teachmehook', handleTeachMe)

isSocketSet.current = true
}
socket.on('teachmehook', handleTeachMe)
}

if (handleInstagraph) {
if (socket) {
socket.on('instagraphhook', handleInstagraph)
socket.on('instagraphhook', handleInstagraph)

isSocketSet.current = true
}
isSocketSet.current = true
}
}, [socket, handleTeachMe, handleInstagraph])

Expand Down
21 changes: 21 additions & 0 deletions src/components/App/Providers/Socket/SocketContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// SocketContext.ts
import { createContext, useContext } from 'react'
import { Socket } from 'socket.io-client'

interface SocketContextType {
socket: Socket
}

const SocketContext = createContext<SocketContextType | undefined>(undefined)

export const useSocket = () => {
const context = useContext(SocketContext)

if (!context) {
throw new Error('useSocket must be used within a SocketProvider')
}

return context.socket
}

export default SocketContext
17 changes: 17 additions & 0 deletions src/components/App/Providers/Socket/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// SocketProvider.tsx
import { FC, ReactNode } from 'react'
import { io } from 'socket.io-client'
import { API_URL } from '~/constants'
import SocketContext from './SocketContext'

interface SocketProviderProps {
children: ReactNode
}

const contextValue = {
socket: io(API_URL),
}

export const SocketProvider: FC<SocketProviderProps> = ({ children }) => (
<SocketContext.Provider value={contextValue}>{children}</SocketContext.Provider>
)
5 changes: 4 additions & 1 deletion src/components/App/Providers/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { ThemeProvider as StyleThemeProvider } from 'styled-components'
import { colors } from '~/utils/colors'
import { breakpoints } from '~/utils/media'
import { MuiButton } from './MuiButton'
import { SocketProvider } from './Socket'

const palette = createPalette({
mode: 'dark',
Expand Down Expand Up @@ -50,7 +51,9 @@ export const AppProviders: FC<PropsWithChildren> = ({ children }) => (
<ThemeProvider theme={appTheme}>
<StyledEngineProvider injectFirst />
<StyleThemeProvider theme={appTheme}>
<LocalizationProvider dateAdapter={AdapterMoment}>{children}</LocalizationProvider>
<LocalizationProvider dateAdapter={AdapterMoment}>
<SocketProvider>{children}</SocketProvider>
</LocalizationProvider>
</StyleThemeProvider>
</ThemeProvider>
)
35 changes: 21 additions & 14 deletions src/components/App/index.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { Suspense, lazy, useCallback, useEffect, useRef } from 'react'
import { Suspense, lazy, useCallback, useEffect } from 'react'
import { FormProvider, useForm } from 'react-hook-form'
import 'react-toastify/dist/ReactToastify.css'
import { Socket } from 'socket.io-client'
import styled from 'styled-components'
import { DataRetriever } from '~/components/DataRetriever'
import { GlobalStyle } from '~/components/GlobalStyle'
import { Flex } from '~/components/common/Flex'
import useSocket from '~/hooks/useSockets'
import { useSocket } from '~/hooks/useSockets'
import { getGraphDataPositions } from '~/network/fetchGraphData/const'
import { useAppStore } from '~/stores/useAppStore'
import { useDataStore } from '~/stores/useDataStore'
Expand All @@ -20,7 +20,6 @@ import { ActionsToolbar } from './ActionsToolbar'
import { AppBar } from './AppBar'
import { DeviceCompatibilityNotice } from './DeviceCompatibilityNotification'
import { Helper } from './Helper'
import { AppProviders } from './Providers'
import { SecondarySideBar } from './SecondarySidebar'
import { Toasts } from './Toasts'

Expand Down Expand Up @@ -77,9 +76,7 @@ export const App = () => {
useDataStore((s) => s.setCategoryFilter),
]

const isSocketSet: { current: boolean } = useRef<boolean>(false)

const socket: Socket | null = useSocket()
const socket: Socket | undefined = useSocket()

const form = useForm<{ search: string }>({ mode: 'onChange' })

Expand Down Expand Up @@ -126,19 +123,29 @@ export const App = () => {

// setup socket
useEffect(() => {
if (isSocketSet.current) {
return
}

if (socket) {
socket.on('newnode', handleNewNode)
socket.on('connect_error', (error: unknown) => {
console.error('Socket connection error:', error)
})

isSocketSet.current = true
socket.on('connect', () => console.log('connected'))

Check warning on line 131 in src/components/App/index.tsx

View workflow job for this annotation

GitHub Actions / build

Unexpected console statement
socket.on('disconnect', () => console.log('disconnected'))

Check warning on line 132 in src/components/App/index.tsx

View workflow job for this annotation

GitHub Actions / build

Unexpected console statement
socket.on('newnode', handleNewNode)
}
}, [socket, handleNewNode])

useEffect(
() => () => {
if (socket) {
console.log('disc')

Check warning on line 140 in src/components/App/index.tsx

View workflow job for this annotation

GitHub Actions / build

Unexpected console statement
socket.disconnect()
}
},
[socket],
)

return (
<AppProviders>
<>
<GlobalStyle />

<DeviceCompatibilityNotice />
Expand Down Expand Up @@ -168,6 +175,6 @@ export const App = () => {
<Helper />
</Wrapper>
</Suspense>
</AppProviders>
</>
)
}
5 changes: 3 additions & 2 deletions src/components/AppContainer/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Suspense, lazy, useState } from 'react'
import { E2ETests } from '~/utils'
import { AppProviders } from '../App/Providers'
import { Auth } from '../Auth'

const LazyApp = lazy(() => import('../App').then(({ App }) => ({ default: App })))
Expand All @@ -8,11 +9,11 @@ export const AppContainer = () => {
const [authenticated, setAuthenticated] = useState(false)

return (
<>
<AppProviders>
<Suspense fallback={<div>Loading...</div>}>
{!authenticated ? <Auth setAuthenticated={setAuthenticated} /> : <LazyApp />}
</Suspense>
<E2ETests />
</>
</AppProviders>
)
}
25 changes: 5 additions & 20 deletions src/hooks/useSockets/index.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,8 @@
// useSocket.ts
import { useContext } from 'react'
import SocketContext from '~/components/App/Providers/Socket/SocketContext'

import { useEffect, useState } from 'react'
import { Socket, io } from 'socket.io-client'
import { API_URL } from '~/constants'
export const useSocket = () => {
const context = useContext(SocketContext)

const useSocket = (): Socket | null => {
const [socket, setSocket] = useState<Socket | null>(null)

useEffect(() => {
const socketInstance = io(API_URL)

setSocket(socketInstance)

return () => {
socketInstance.disconnect()
}
}, [])

return socket
return context?.socket
}

export default useSocket

0 comments on commit 5ddd899

Please sign in to comment.