So I have a project component that is getting data from my Project context. And I'm trying to select the first object in that array of objects and pass it to a new state.
Project Component
const projects = useContext(ProjectContext) // array of objects from context
const [selected, setSelected] = useState({}) // where i will pass projects[0]
const selectProj = (data) => {
setSelected(data) // INFINITE LOOP ERROR
}
if (projects.length > 0) {
selectProj(projects[0])
}
So I'm kinda lost here on what todo.
Update: Answer I Used
const projects = useContext(ProjectContext) // array of objects
const [selected, setSelected] = useState({})
const selectProj = (data) => {
setSelected(data)
}
useEffect(() => {
if (projects.length > 0) {
selectProj(projects[0])
}
}, [projects])
You're getting into an infinite loop because setSelected
causes a re-render, and on the re-render projects.length
is greater than 0 again, which causes another re-render, and so on.
One way to avoid this is by calling selectProj
only if there's no project already selected:
if (!selected && projects.length > 0) {
selectProj(projects[0]);
}
don't change state on render, you can do it in useEffect
or give a initial value
useEffect(()=> {
setSelected(projects[0])
}, [])
or
const [selected, setSelected] = useState(projects[0]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.