-
Hi, I have some data(a list of objects) I am fetching via useQuery and I want the user to be able to modify this list and submit it as a form, so i am saving it via useState. From my understanding, props in react don't sync with state unless i do something like using useEffect like below. Reason I am doing this is because data is initially undefined, so i need to seed the state with the updated data once it actually comes back. I was referencing this article from tk: https://tkdodo.eu/blog/putting-props-to-use-state and pretty much the useEffect is seen as a bad idea and anti-pattern. Im wondering if there is an alternative solution ? export const useRooms = (projectID: string) => {
const {
data: initialRooms,
isLoading,
isPending: isRoomsPending,
isError: isRoomsError,
} = useQuery({
queryKey: ['rooms', projectID],
queryFn: () => getRooms(projectID),
placeholderData: [],
select: (data) => {
return data.map((r) => ({
label: r.room,
value: r.room,
include: r.include,
}))
},
})
const preSelected = initialRooms
.filter((r) => r.include)
.map((r) => ({ label: r.label, value: r.label }))
return { initialRooms, preSelected, isRoomsPending, isRoomsError }
}
export const useSaveRooms = (preSelected: Room[]) => {
const [selectedRooms, setSelectedRooms] = useState(preSelected)
useEffect(() => {
if (preSelected.length > 0 && selectedRooms.length === 0) {
setSelectedRooms(preSelected)
}
}, [preSelected]) Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
I have a blogpost on this: |
Beta Was this translation helpful? Give feedback.
no, it really isn’t: