How to use an API webhook in React to receive notifictions
Asked Answered
T

2

15

This is my first time working with Webhooks and I was wondering if it was possible to receive notifcations from a Webhooks subscription. I'm using create-react-app for my project and want to use github's Webhooks subscription to send an alert everytime I commit to my github repository. How would I tackle this project and what would I need to do to test my Webhooks subscription?

Trujillo answered 14/5, 2020 at 4:23 Comment(0)
W
9

I hope this tip helps! Let's get to it ...

I suggest using a web socket, where your application will be listening to the back end.

This will prevent you from creating request loops for the backend.

Additional information...

React only consumes information, who provides and controls is only the backend.

Hope this helps. Success!

class Main extends Component {
    ......
    // instance of websocket connection as a class property
    ws = new WebSocket('ws://localhost:3000/ws')
    componentDidMount() {
        this.ws.onopen = () => {
        // on connecting, do nothing but log it to the console
        console.log('connected')
        }
        this.ws.onmessage = evt => {
        // listen to data sent from the websocket server
        const message = JSON.parse(evt.data)
        this.setState({dataFromServer: message})
        console.log(message)
        }
        this.ws.onclose = () => {
        console.log('disconnected')
        // automatically try to reconnect on connection loss
        }
    }
    render(){
        <ChildComponent websocket={this.ws} />
    }
}

In the example I used a class component. A tip to take advantage of modern features would be to start with functional components.

UPDATE 2023

It's been a few years since this topic was answered, I see that there are still people with related questions. I will add a basic update to functional components that is more modern than the old class components.

export const MyFunctionalComponent = () => {

  const handleWebSocket = () => {
    const newSocket = new WebSocket("ws://localhost:8080/ws");
    newSocket.onopen = () => console.log('WS Connected');
    newSocket.onclose = () => console.log('WS Disconnected');
    newSocket.onerror = (err) => console.log("WS Error");
    newSocket.onmessage = (e) => {
      const data = JSON.parse(e.data);
      console.log("WS Receives: ", data);
    }
  }

  useEffect(() => { 
    handleWebSocket();
  }, []);
}

Success on your development journey! 🙂

Warhol answered 14/5, 2020 at 4:48 Comment(2)
Is a 2023 version with React Hooks available?Saltatory
This is my functional components version of websocket: useEffect(() => { const newSocket = new WebSocket("ws://localhost:8080/ws") newSocket.onopen = () => console.log('connected'); newSocket.onclose = () => console.log('disconnected'); newSocket.onerror = (err) => console.log("ws error"); newSocket.onmessage = (e) => { const msgObj = JSON.parse(e.data); console.log("ws receives msgObj: ", msgObj); ... return () => { newSocket.close(); }; }, []);Colby
C
0

Not answering the op's question, I just want to provide my functional component version of websocket to complement the answer above: https://mcmap.net/q/785162/-how-to-use-an-api-webhook-in-react-to-receive-notifictions:

useEffect(() => {
    const newSocket = new WebSocket("ws://localhost:8080/ws")
    newSocket.onopen = () => console.log('connected');

    newSocket.onclose = () => console.log('disconnected');

    newSocket.onerror = (err) => console.log("ws error");

    newSocket.onmessage = (e) => {
        const msgObj = JSON.parse(e.data);
        console.log("ws receives msgObj: ", msgObj);
        ...

    return () => {
        newSocket.close();
    };
}, []);
Colby answered 1/12, 2023 at 23:35 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.