Reputation: 565
I wanna access an array called "currentNode" from the react context, but looks like it does not work. The console error message is the following:
Unhandled Rejection (TypeError): Cannot read property '0' of null.
It seems that I cannot access the currentNode variable from the context. Can you identify the mistake? Help is very much appreciated.
Step 1: Here is the code, how I dispatch it to the context:
const AuthState = (props) => {
// auth state: create initial authState
const initialState = {
isAuthenticated: false,
chatId: null,
currentNode: [],
};
const fetchCurrentNode = async (chatId) => {
try {
const config = {
headers: {
"x-auth-token": "",
},
};
const res1 = await axios.get(
`http://localhost:4001/api/chatbots/${chatId}/nodeid`,
//`https://mybot.uber.space/api/chatbots/${chatid}`
//`https://sandbox.as.wiwi.uni-goettingen.de/teachr/chatbots/pin/${pin}`
config
);
dispatch({
type: NEW_CURRENT_NODE_CREATED,
payload: currentNode,
});
} catch (error) {
console.error(error);
}
};
return (
<ChatContext.Provider
value={{
chatId: state.chatId,
chat: state.chat,
chatSessionId: state.chatSessionId,
createChatSessionId,
addBackendAnswerToChat,
addUserInputToChat,
resetChat,
fetchEventAnswerFromDialogflow,
fetchAnswerFromDialogflow,
}}
>
{props.children}
</ChatContext.Provider>
);
};
Step 1b: Here is my context declaration:
import React from 'react';
const chatContext = React.createContext();
export default chatContext;
Step 2: Here is how I saved it as Types:
export const NEW_CURRENT_NODE_CREATED = "NEW_CURRENT_NODE_CREATED";
Step 3: Here is my reducer function:
import { CHATID_FETCH_SUCCESSFUL, NEW_CURRENT_NODE_CREATED } from "./authTypes";
export default (state, action) => {
switch (action.type) {
case NEW_CURRENT_NODE_CREATED:
return {
...state,
isAuthenticated: true,
currentNode: [action.payload],
};
default:
return state;
}
};
Step 4: And here is how I wanna get access to the currentNode variable:
import AuthContext from "../../Context/Auth/authContext";
const authContext = useContext(AuthContext);
const { chatId, currentNode } = authContext;
console.log(chatId);
console.log(currentNode);
Upvotes: 0
Views: 278
Reputation: 2865
You didn't add value you are trying to use to the context value
return (
<ChatContext.Provider
value={{
chatId: state.chatId,
chat: state.chat,
currentNode: state.currentNode, // <-- ADD THIS LINE
chatSessionId: state.chatSessionId,
createChatSessionId,
addBackendAnswerToChat,
addUserInputToChat,
resetChat,
fetchEventAnswerFromDialogflow,
fetchAnswerFromDialogflow,
}}
>
{props.children}
</ChatContext.Provider>
);
};
Upvotes: 1