I’m making a React game where you are a 911 dispatcher and have to communicate with other people through a chat box. The game has different callouts/situations and I want everything to be as organised as possible. In the “App.jsx” file I created a hook which manages the chat (“const [chat, setChat] = useState()”). The problem appears when, since I want to store each callout in a different file, like “Callout1.js”, “Callout2.js” (in each file there will be data related to that callout like what the caller is going to say, where the location of the emergency is, etc.), I try calling “chat” or “setChat” from another file.
It returns an error: "Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component [...]"
.
This is a part of my code to help you understand what I’m trying to achieve:
“App.jsx”, where all the text messages are shown:
export const Chat = () => {
const [chat, setChat] = useState([
{
text: "Hello",
},
{
text: "Hello 1",
},
]};
return { call, setCall };
};
const App = () => {
[...]
<div>
{chat.map((msg, i) => (
<p key={i}>{msg.text}</p> // Display all messages in chat
))}
</div>
))}
[...]
“Callout1.js”, from where I would like to call “setChat” in order to add messages for this callout specifically:
import { Chat } from "../App";
export const startChat = () => {
const { chat, setChat } = Chat();
setChat(prev => ([...prev, {text: "Hello from Callout1"}])); // add message to chat from Callout1.js
};
When I call “startChat” from “App.jsx”, it gives me the error. How can I solve it while being able to update the chat no matter what file I’m calling it from?