Edit: It's working on enter of submit, but not letting me input characters
I'm not sure why I am getting an error saying Cannot read property 'onKeyPressHandler' of undefined
React, and Nextjs, Socket.io, and Express are some of the things I am using.
I am trying to have so whenever you hit enter a chat message will be sent but I am getting that error, and I am not too sure why.
Sorry this is probably a super simple question, It's just super late so my brain is a little tired ha!
This is the file that the input logic is in chat.js :
import React from "react";
import styled from "styled-components";
import Sidebar from "../components/Sidebar";
import UserMessage from "../components/UserMessage";
import { Store, CTX } from '../components/Store'
const ChatBox = (props) => {
const [textValue, changeTextValue] = React.useState('');
const { allChats } = React.useContext(CTX);
console.log(allChats)
const onKeyPressHandler = (e) => {
if (e.key === 'Enter') {
sendChatAction(textValue)
changeTextValue('')
}
}
return (
<Layout>
<Sidebar />
<Wrapper>
<InnerBoxWrapper>
<InnerBox>
<UserMessage />
<input label="Send a chat" value={textValue} onKeyPress={onKeyPressHandler} />
</InnerBox>
</InnerBoxWrapper>
</Wrapper>
</Layout>
)
}
export default (props) => <Store><ChatBox {...props} /></Store>
Here I'll also show the store just in-case for some reason the context is causing it?
Store.js -
import React from 'react'
import io from 'socket.io-client'
export const CTX = React.createContext();
const initState = {
general: [
{ from: 'user1', msg: 'hello' },
{ from: 'user2', msg: 'u stink' },
{ from: 'user3', msg: 'some other words' }
],
channel2: [
{ from: 'user1', msg: 'hello' }
]
}
const reducer = (state, action) => {
const { from, msg, channel } = action.payload;
switch (action.type) {
case 'RECEIVE_MESSAGE':
return {
...state,
[channel]: [
...state[channel],
{ from, msg }
]
}
default:
return state
}
}
const sendChatAction = (dispatch, socket) => {
socket.emit('chat message', value);
}
let socket;
export const Store = (props) => {
if (!socket) {
socket = io(':3001')
}
const [allChats, dispatch] = React.useReducer(reducer, initState)
return (
<CTX.Provider value={{ allChats, sendChatAction }}>
{props.children}
</CTX.Provider>
)
}
this, so useonKeyPress={onKeyPressHandler}