i can't use dispatch inside useEffect as soon as i add that line its shows me this error
import { useDispatch } from 'react-redux'
import db from '../firebase'
import setProjects from '../features/projects/projectSlice'
function Home (){
const dispatch = useDispatch();
let projects = [];
useEffect(() => {
db.collection('projects').onSnapshot((snapshot) => {
snapshot.docs.map((doc) => {
// eslint-disable-next-line default-case
switch(doc.data().type){
case 'clone':
projects = [...projects, { id: doc.id, ...doc.data()}];
break;
}
});
dispatch(setProjects({
project : projects,
}))
});
}, []);
this is my slice code
import { createSlice } from '@reduxjs/toolkit'
const initialState = {
project : null,
}
const projectSlice = createSlice({
name: 'project',
initialState,
reducers: {
setProjects: (state,action) => {
state.project = action.payload.project;
},
},
});
export const {setProjects} = projectSlice.actions
export default projectSlice.reducer;
I want to push the data from projects array to project array of the slice so i can use it elsewhere but when i use the dispatch; it shows me this error
TypeError: Cannot read properties of undefined (reading 'type')
Can anyone help me with my error , im stack for ages :(
CodePudding user response:
Your exporting setProjects
as a named export but trying to import it as a default export.
import { useDispatch } from 'react-redux'
import db from '../firebase'
import setProjects from '../features/projects/projectSlice'
You need to import setProjects
like this...
import { setProjects } from '../features/projects/projectSlice'
More info on named vs default exports.