Reputation: 47
Beginner in reactjs and have tried everything I could. The 'contacts' is always undefined. Note that i've removed some unrelated code and have only pasted relevant code here.
Thanks in advance
const initialState = {
contacts: ["[email protected]"],
loggedInUser: null,
isChatPage: true
}
const [state, dispatch] = useReducer(chatReducer, initialState);
useEffect(() => {
console.log(state.contacts);
}, [state]);
const setContacts = (contactList) => {
console.log(contactList);
dispatch({
type: SET_CONTACT_LIST,
payoad: contactList
})
}
the userReducer function is
const chatReducer = (state, action) => {
console.log(action);
console.log(state);
switch(action.type) {
case TOGGLE_CHAT:
return {
...state,
isChatPage: action.payload
}
case SET_LOGGED_USER:
return {
...state,
loggedInUser: action.payload
}
case SET_CONTACT_LIST:
return {
...state,
contacts: action.payload
}
}
}
And the setContact is called from another file as below:
const context = useContext(ChatContext);
const updateRealTimeUsers = () => {
db.collection("users")
.get()
.then((querySnapshot) => {
var users = [];
querySnapshot.forEach((doc) => {
users.push(doc.data().email);
});
console.log("Current users: ", users);
context.setContacts(users);
});
}
useEffect(() => {
updateRealTimeUsers();
// console.log(contacts);
}, []);
And the logging from chatReducer is below:
{type: "SET_CONTACT_LIST", payoad: Array(3)}
payoad: (3) ["[email protected]", "[email protected]", "[email protected]"]
type: "SET_CONTACT_LIST"
[[Prototype]]: Object
chat-reducer.js:5
{messages: Array(13), chats: Array(12), users: Array(7), contacts: null, contactsDummy: Array(1), …}
chats: (12) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
contacts: null
isChatPage: true
loggedInUser: {email: "[email protected]", uid: "0aic691KY4ZmJDXv3T6mji9qZnO2"}
messages: (13) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
test: (3) [1, 2, 3]
user: {}
users: (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
Upvotes: 0
Views: 32
Reputation: 1306
I think you have a typing mistake in setContacts
. You write payoad
instead of payload
!
const setContacts = (contactList) => {
console.log(contactList);
dispatch({
type: SET_CONTACT_LIST,
payoad: contactList
})
}
Upvotes: 1