How to solve TypeError: arr[Symbol.iterator] is not a function in my React project
Answer a question
I am encountering this error while following this tutorial. I have so far followed his code exactly but he does not get this error. I am at 2:09:30 in the tutorial.
I've looked through all my hooks and all the variables and types seem to be correct. I thought it might be an error with setSelectedProject() but this line of investigation did not prove fruitful. allProjects and projects are definitely arrays...
IndividualProject.js
export const IndividualProject = ({ project }) => {
const [showConfirm, setShowConfirm] = useState(false);
const [projects, setProjects] = useProjectsValue();
const { setSelectedProject } = useSelectedProjectValue();
console.log("Projects: ", projects);
const deleteProject = docId => {
firebase
.firestore()
.collection("projects")
.doc(docId)
.delete()
.then(() => {
setProjects([...projects]);
console.log("Projects from IndividualProject: ", project);
setSelectedProject("Inbox");
});
};
...
src/hooks/Index.js
export const useProjects = () => {
const [projects, setProjects] = useState([]);
useEffect(() => {
firebase
.firestore()
.collection("projects")
.where("userId", "==", "PO1n5mxjYYpcnq9joPZl")
.orderBy("projectId")
.get()
.then(snapshot => {
const allProjects = snapshot.docs.map(project => ({
...project.data(),
docId: project.id
}));
console.log(typeof allProjects);
if (JSON.stringify(allProjects) !== JSON.stringify(projects)) {
setProjects(allProjects);
}
});
}, [projects]);
return { projects, setProjects };
};
Projects.js
export const Projects = ({ activeValue = null }) => {
const [active, setActive] = useState(activeValue);
const { setSelectedProject } = useSelectedProjectValue();
const { projects } = useProjectsValue();
return (
projects &&
projects.map(project => (
<li
key={project.projectId}
data-doc-id={project.docId}
data-testid="project-action"
className={
active === project.projectId
? "active sidebar__project"
: "sidebar__project"
}
onClick={() => {
setActive(project.projectId);
setSelectedProject(project.projectId);
}}
>
<IndividualProject project={project} />
</li>
))
);
};
Here is a full screenshot of the error output upon compiling.
Answers
The way you're consuming the return values in the IndividualProject component of your useSelectedProjectValue custom hook is wrong:
const [projects, setProjects] = useProjectsValue();
should be
const { projects, setProjects } = useProjectsValue();
React uses array destructuring e. g. for their useState, but your useSelectedProjectValue hook is rather returning an object and not an array, so you have to consume it in the components with object desctructuring. Or change the return value of the custom hook to an array.
If you want to learn more about this topic I recommend reading Kent C. Dodds' blog: https://kentcdodds.com/blog/react-hooks-array-destructuring-fundamentals
更多推荐
所有评论(0)