I can't update my array inside my context.
I've tried with spread and concat, but doesn't work.
Please consider that context are working fine, Also consider that I've tried both filter and find, and both are entering on if consitional, however is not saving a new value to the state.
My function:
const createChatDetailRegister = async (channelSid: string) => {
const existsChannelInfo = chatDetails.filter(chatInfo => chatInfo.channelSid === channelSid);
if (existsChannelInfo.length < 1) {
const chatInfo = { channelSid, isChatOpen: true };
setChatDetails(prevstate => [...prevstate, chatInfo]);
}
My state:
const [chatDetails, setChatDetails] = useState([]);
My entire context:
import React, { createContext, ReactNode, useState } from 'react';
interface ChatContextData {
createChatDetailRegister: (channelSid: string) => void;
}
interface ChatProviderProps {
children: ReactNode;
}
export const ChatContext = createContext({} as ChatContextData);
export function ChatProvider({ children }: ChatProviderProps) {
const [chatDetails, setChatDetails] = useState([]);
const createChatDetailRegister = async (channelSid: string) => {
const existsChannelInfo = chatDetails.filter(chatInfo => chatInfo.channelSid === channelSid);
if (existsChannelInfo.length < 1) {
const chatInfo = { channelSid, isChatOpen: true };
setChatDetails(prevstate => [...prevstate, chatInfo]);
}
};
return (
<ChatContext.Provider
value={{
createChatDetailRegister,
}}
>
{children}
</ChatContext.Provider>
);
}
By the way i'm importing the provider in my app file
App file:
import React from 'react';
import App from 'next/app';
import './app.css';
import 'react-toastify/dist/ReactToastify.css';
import { ChatProvider } from '../components/context/Chat';
class MyApp extends App {
constructor(props) {
super(props);
}
render() {
const { Component, pageProps } = this.props;
return (
<ChatProvider>
<Component {...pageProps} />
</ChatProvider>
);
}
}
export default MyApp;
The place where I call my context, index.tsx:
import { ChatContext } from 'components/context/Chat';
import React, { useContext } from 'react';
import { Container, ButtonContainer } from './styles';
import { ProjectMembersChatButtonsProps } from './types';
const ProjectMembersChatButtons: React.FC<ProjectMembersChatButtonsProps> = () => {
const { createChatDetailRegister } = useContext(ChatContext);
return (
<Container>
<ButtonContainer
onClick={() => {
createChatDetailRegister('1279812931');
}}
></ButtonContainer>
</Container>
);
};
export default ProjectMembersChatButtons;