pusher is sending message two times on submit. i dont see any function being repeated or called two times but this still happens
i am using React v18.1.0 i am using Golang 1.18
import React, { useState, useEffect } from "react";
import Pusher from "pusher-js";
function App() {
const [username, setUsername] = useState('username');
const [messages, setMessages] = useState([]);
const [message, setMessage] = useState('');
let allMessages = [];
useEffect(() => {
Pusher.logToConsole = true;
const pusher = new Pusher('-', {
cluster: '-'
});
const channel = pusher.subscribe('chat');
channel.bind('message', function (data) {
allMessages.push(data);
setMessages(allMessages);
});
}, []);
const submit = async e => {
e.preventDefault();
await fetch('http://localhost:8000/api/messages', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
username,
message
})
});
setMessage('');
}
return (
<div className="container">
<div className="d-flex flex-column align-items-stretch flex-shrink-0 bg-white">
<div
className="d-flex align-items-center flex-shrink-0 p-3 link-dark text-decoration-none border-bottom">
<input className="fs-5 fw-semibold" value={username}
onChange={e => setUsername(e.target.value)}/>
</div>
<div className="list-group list-group-flush border-bottom scrollarea">
{messages.map(message => {
return (
<div className="list-group-item list-group-item-action py-3 lh-tight">
<div className="d-flex w-100 align-items-center justify-content-between">
<strong className="mb-1">{message.username}</strong>
</div>
<div className="col-10 mb-1 small">{message.message}</div>
</div>
)
})}
</div>
</div>
<form onSubmit={e => submit(e)}>
<input className="form-control" placeholder="Write a message" value={message}
onChange={e => setMessage(e.target.value)}
/>
</form>
</div>
);
}
export default App;
this is my backend code in Golang
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/pusher/pusher-http-go"
)
func main() {
app := fiber.New()
app.Use(cors.New())
pusherClient := pusher.Client{
AppID: "1421095",
Key: "-",
Secret: "-",
Cluster: "ap2",
Secure: true,
}
app.Post("/api/messages", func(c *fiber.Ctx) error {
var data map[string]string
if err := c.BodyParser(&data); err != nil {
return err
}
pusherClient.Trigger("chat", "message", data)
return c.JSON([]string{})
})
app.Listen(":8000")
}
ive searched alot online but i can really find a solution. above is all the code ive written to create the app
CodePudding user response:
OK I got it. I had my App.js wrapped in React Strict Mode in index.js. It was causing my Page to render 2 times this the useEffect function was running two times. So if anyone is having this issue, make sure you are not using React Strict Mode