React+vite application is unable to establish a WebSocket connection with a Spring Boot backend server

My React + Vite application is running on localhost:5173 port, while my Spring Boot is running on localhost:5729. Here is the code snippet from the App.jsx:

import { useState } from 'react'
import './App.css'

function App() {
  const [list, setList] = useState([])

  var ws = new WebSocket("ws://localhost:5729/cp")

  ws.onmessage=(message)=>{console.log(message); setList([...list,message])};

  return (
    <ul>
      {list.map(element => {
        return (<li>element</li>);
      })
    }
    </ul>
  )
}

export default App

This is the setup in my Spring Boot configuration:

@Configuration
@EnableWebSocket
//@ServerEndpoint("/cp")
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new Handler(),"/cp");
    }


    class Handler extends TextWebSocketHandler {

        private List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
        @Override
        public void afterConnectionEstablished(WebSocketSession session) {
            System.out.println("Session Added: "+session.getId());
            sessions.add(session);
        }

        @Override
        public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
            System.out.println("Closed");
        }

        @Override
        protected void handleTextMessage(WebSocketSession session, TextMessage message){
            for(var t: sessions){
                try {
                    t.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

I started the Spring Boot application first, followed by running the React application. However, when I checked the console in my React app, it displayed the following error messages:

App.jsx:7 WebSocket connection to 'ws://localhost:5729/cp' failed: 
App.jsx:7 WebSocket connection to 'ws://localhost:5729/cp' failed:

I have attempted a clean build using Maven, but the issue persists. Additionally, there are no logs or indications of activity in my Spring Boot app when the React app is running.

Oddly enough, I am able to successfully connect using Postman to the specified endpoint.

Answer №1

Instead of creating a new websocket instance every time your app component updates with setList, consider initializing it within the useEffect hook without a dependency list to ensure it only gets created once when the app component is loaded:

useEffect(() => {
  let ws = new WebSocket("ws://localhost:5729/cp");
  ws.onmessage=(message)=>{console.log(message); setList([...list,message])};
}, []);

This may not solve your connection issue, but it's something to address for future improvements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to nest slices within slices? What is the best way to distribute shared state logic among slices?

EDIT: I am currently attempting to implement this functionality using Redux Access the codesandbox here. For a quick visual reference, visit: https://jsfiddle.net/59r31Lmt/ I am aiming to create a system where clicking on a camo square activates it. Th ...

Generate a fresh Date/Time by combining individual Date and Time components

I have set up a form to gather dates from one input box and times from another. var appointment_date = new Date(); var appointment_start = new Date("Mon Apr 24 2017 20:00:00 GMT-0400 (EDT)"); var appointment_end = new Date("Mon Apr 24 2017 21:30:00 GMT- ...

Exploring FileReader in conjunction with React and Typescript

I am facing an issue while trying to upload a JSON file using an input element of type file. When I attempt to use the onload method on FileReader in TypeScript, I receive an error message saying "Cannot invoke an object which is possibly 'null'. ...

Testing a React component using the `ua-parser-js` plugin with Jest and React Testing Library

I've developed a simple component that displays an image depending on the operating system you are using (in this case, iOS and Android). import { UAParser } from "ua-parser-js"; export const DownloadApp = ({ appleStoreUrl, playStoreUrl }: ...

Utilizing an arrow function enclosed within curly brackets to manage React context

During a React context tutorial, I came across this code snippet: <MyContext.Consumer> {value => /* render something based on the context value */} </MyContext.Consumer> This part, value => /* render something based on the context valu ...

Encountering a missing semicolon error while attempting to dynamically define props in React

I'm currently working with apexcharts to generate a chart. My goal is to define the chart items using props, and I am attempting to use a prop like this: series = {[{}]}. The series prop is expected to be an array, where each element in the array is ...

Changing date format in Mui DatePicker

I need some assistance with customizing the mui DatePicker. Specifically, I would like to set the date format to display as Day, DD Month. For example: Monday, 10 September Below is the code snippet I am currently working with: <LocalizationProvider d ...

React applications leveraging ES6 binding patterns

When examining various React code examples, a common pattern that emerges is the following: class Foo extends Component { constructor() { this.someMethod = this.someMethod.bind(this); } someMethod() { } <Bar doSomething={this.someMetho ...

Utilize State Hooks with arrays and objects

***I'm looking to define the initial state as an array with two objects, each containing another array. However, I'm having trouble setting this state using setState. The state I am trying to set should consist of two objects, each with two prop ...

What causes the circular progress bar to disappear when hovering over the MUI React table?

My goal was to create a table with a CircularProgressBar that changes its background color from orange to dark blue when hovering over the row. However, despite my efforts, I couldn't get it to work as intended. Additionally, I wanted the progressBar ...

Next.js - Anticipated that the server HTML would include a corresponding <div> within <div> tag

For a live demonstration, please click here In my current project, I am experimenting with creating a simple layout that adjusts based on the user's screen size. Specifically, on mobile devices, only the latest posts should be displayed. On desktops, ...

Troubleshooting a Proxy Error while deploying a React, Express, and Node app to Heroku

In the past, I've successfully deployed full stack applications to Heroku by including a proxy link in the client's package.json file. However, recently I encountered an "Invalid Host header" error. To resolve this issue, I removed the proxy and ...

What is the best way to apply styles when a component is hovered over in the DataPicker material-ui component?

If you want to see a live demo, click here My preference is to modify the border color, label text color, and down icon color on hover. Currently, the default style is in place but I'm wondering if I can change it back to blue? https://i.stack.imgu ...

Having trouble with nextjs routes not displaying the Modal?

Struggling to get the intercepting routes feature of Next.js' new app router to work with a Modal. The issue is, the Modal never renders and only the URL changes. My project structure is as follows: /app @modal (.)user [id] page.js user [ ...

Several mistakes occurred involving auth0, react, apollo, babel, and webpack

I seem to be facing some challenges while trying to integrate auth0 into my project. Every time I fix one issue, another one pops up and it's always the same trio of errors: -require is not a function -window is not defined -missing class properties ...

Having difficulties in storing the checkbox selections

Whenever I switch components and return back, the checkboxes do not persist. I want to ensure that the checked checkboxes stay checked. For more information and code samples, you can visit this CodeSandbox link: CodeSandbox Link. courses.js import React ...

Encountering a SignatureDoesNotMatch error when trying to upload an image to S3 using a presigned URL with ReactJs/NodeJS

After successfully integrating image upload to S3 using a pre-signed URL in App1, I attempted the same process in App 2, only to encounter the recurring error: 403 SignatureDoesNotMatch FRONTEND: import React from "react"; import { uploadAdIma ...

Navigating to a different component with react-bootstrap-table-next?

I have a collection of coding challenges in a table format. I want the user to be able to click on a challenge name and be routed to a separate page showcasing the details of that specific problem using a Problem component with unique props. Currently, I ...

Switching tabs in React using Material UI checkboxes causes the check mark to disappear visually

I've been struggling with this issue for quite some time - I have checkboxes (50) rendered within a tab, and after checking them, switching tabs, and then going back, the value is stored but the checkbox loses its visual appearance. <Tabs value={se ...

Using React Router to transmit information

My React router setup is pretty straightforward: <Route handler={AppRoot}> <Route name="about" handler={About} /> <Route path="/projects" handler={Projects} /> <Route path="/projects/experiments" handler={Projects} /> & ...