Ok so here's the repo: https://github.com/bigolboyyo/phase2final/tree/projectbranch5
I'm in a boot camp and working on a live chat app. For some reason even though state is being (assumingly) updated when I POST/Fetch the data is lagging behind.
I have 2 separate chat routes. One that starts a chat based on a reddit thread id and another that you can manually enter a room id to join.
In my logs the redditRoom state is being updated immediately before the fetch happens, yet when the POST/Fetch happens it takes a second event (button click) and it sends the previous redditRoom state.
Know this is a little long winded, but even any ideas or pointers in the right direction would be amazing.
If there is any other context I can provide please let me know, still a new dev and working on composing better posts. Thanks in advance!
App.js
const [showChat, setShowChat] = useState(false);
const [redditRoom, setRedditRoom] = useState("");
const [redditTitle, setRedditTitle] = useState("");
const [room, setRoom] = useState("");
const [artRef, setArtRef] = useState({});
const [userName, setUserName] = useState("");
const userData = {
userName: userName,
room: room,
redditRoom: redditRoom,
};
function postUserDB() {
fetch("http://localhost:3004/userData", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(userData),
})
.then((response) => response.json())
.then((data) => {
console.log("Success:", data);
})
.catch((error) => {
console.error("Error:", error);
});
}
RedditPosts.js
function handleChatClick() {
socket.emit("join_room", article.id);
console.log(article.id);
setRedditRoom(article.id);
setRedditTitle(article.title);
setArtRef(article);
navigate("/redditchat");
}
function handleAndUpdate() {
handleChatClick();
postUserDB();
}
/redditchat route
<Route
path="/redditchat"
element={
<RedditChat
socket={socket}
redditRoom={redditRoom}
artRef={artRef}
userName={userName}
/>
button
<button
onClick={handleAndUpdate}
style={{ padding: "1rem" }}
id="start-chat"
>
Start Chat
</button>