I have a component that is getting is state from redux. I have a provider that is dispatching an action to get state, then is passing that state down to this component with useContext This works on every other render which is weird.... refresh, get TypeError: Cannot read properties of undefined (reading 'find') refresh, works fine. refresh, works fine. refresh, get TypeError: Cannot read properties of undefined (reading 'find') refresh works, fine.
The problem is when I try to run a find on the state, I get the error
Im guessing the state is not updating fast enough and the computer is trying to forEach over something that doesn't exist?
Here is my code below
import React, { useContext } from 'react';
import { ChatContext } from '../../../context/Context';
const ChatConversation = ({ conversation }) => { // mapped over a "conversations array" is component above this one and pass a conversation ---> looks like [ 'Oxt56Beix' ]
const { conversationMessages } = useContext(ChatContext);
const message = conversationMessages.find(({ messagesId }) => messagesId === conversation.messagesId); // this find is throwing error every other render or so
return (
<div>
<h2>{message}</h2>
</div>
)
{
here is my conversationMessages reducer
import { LIST_CONVERSATION_MESSAGES } from '../actions/types';
export default function (state = [ {
messagesId: 1,
content: []
}, action) {
switch (action.type) {
case LIST_CONVERSATION_MESSAGES:
return action.payload
default:
return state;
}
}
Here is a snapshot of my Provider wrapping this component
import React, { useState, useEffect } from 'react';
import {useSelector, useDispatch} from 'react-redux';
import { ChatContext } from '../../context/Context';
const ChatProvider = ({ children }) => {
const conversationMessages = useSelector((state) => state.conversationMessages)
useEffect(() => {
dispatch(listConversationMessages())
}, [])
useEffect(() => {
dispatch(listConversations())
}, [])
const value = {
conversations,
conversationMessages,
};
return <ChatContext.Provider value={value}>{children}</ChatContext.Provider>;
};
export default ChatProvider;
My Problem was in my reducer.
My action.payload was coming back as an OBJECT
Even though In my backend function I was res.json with an array, the action.payload was an OBJECT that CONTAINED the array in a data key
I changed my reducer to
import { LIST_CONVERSATION_MESSAGES } from '../actions/types';
export default function (state = [ {
messagesId: 1,
content: []
}, action) {
switch (action.type) {
case LIST_CONVERSATION_MESSAGES:
return action.payload.data // solution was to use action.payload.data instead of action.payload
default:
return state;
}
}```