How to easily insert, update, and delete with supabase realtime (Using react and next.js) #28484
Quarantiine
started this conversation in
Contribute to Supabase
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I was having trouble on how to deal with realtime changes that you can actually see on the web page. I
console.log
the realtime changes but it didn't seem to show the changes on the web page, so I took time to figure out how to do it.(Only works with react.js, next.js, javascript, and typescript | Make sure to Disable RLS for this to work):
Supabase Realtime Insert:
useEffect(() => { const channels = supabase .channel("[any name]") .on( "postgres_changes", { event: "INSERT", schema: "public", table: "[table name]" }, (payload) => { setData((prev: any) => { return [ ...prev.filter((value: any) => value).map((value: any) => value), payload.new, ]; }); } ) .subscribe(); return () => { channels.unsubscribe(); }; }, []);
Supabase Realtime Delete:
useEffect(() => { const channels = supabase .channel("[any name]") .on( "postgres_changes", { event: "DELETE", schema: "public", table: "[table name]" }, (payload) => { setData((prev: any) => { return prev .filter((value: any) => value.id !== payload.old.id) .map((value: any) => value); }); } ) .subscribe(); return () => { channels.unsubscribe(); }; }, []);
Supabase Realtime Update:
useEffect(() => { const channels = supabase .channel("[any name]") .on( "postgres_changes", { event: "UPDATE", schema: "public", table: "[table name]" }, (payload) => { setData((prev: any) => { const updatedPeople = prev?.map((user: any) => user.name === prev ?.filter((value: any) => value.id === payload.old.id) ?.map((value: any) => value.name) .toString() ? { ...user, name: payload.new.name } : user ); return updatedPeople; }); } ) .subscribe(); return () => { channels.unsubscribe(); }; }, []);
FYI: Make sure to use prettier to make it look better. Hope this helps because it helped me. Change the values [any name] & [table name] to what you need them to be. The state
setData
is basically the data from your supabase database inside of a useState.Beta Was this translation helpful? Give feedback.
All reactions