import React ,{useEffect, useState}from 'react'
import Layout from '../components/Layout'
import axios from 'axios';
import TinderCard from 'react-tinder-card'
import MovieCard from '../components/MovieCard';
import { createClient } from '@supabase/supabase-js'
import { useAuth } from '../auth';
function Home() {
const auth = useAuth();
const supabaseUrl = process.env.REACT_APP_SUPABASE_URL
const supabaseKey = process.env.REACT_APP_SUPABASE_KEY
const supabase = createClient(supabaseUrl, supabaseKey)
const [movies, setMovies] = useState([])
const [message, setMessage] = useState("")
const fecthMovies = async () => {
const {data} = await axios.get("https://api.themoviedb.org/3/discover/movie",{
params:{
page:Math.random() * 501,
api_key:"57e19e5c44a33653ce6bfc54743c9e2e"
}
})
console.log(data);
const movie = await data;
setMovies(movie.results);
}
const addTowatchlist = async (movie) => {
const {data, error} = await supabase.from("watchlists").insert({movie_id : movie.id, user_id: auth.user.id})
if(error){
console.log(error)
}
if(data){
setMessage("Movie has been added to your watchlist")
}
}
useEffect(() => {
if(auth.user){
fecthMovies()
}
},[auth])
return (
<Layout>
{message&&message}
<h1>Welcome</h1>
{!auth.user && <h2>Please sign up</h2>}
{movies.map(movie => {
return <>
<div className="movie-wrapper">
<TinderCard
onSwipe={direction => direction === "right"? addTowatchlist():null}
key={movie.id}>
<MovieCard movie={movie}/>
</TinderCard>
</div>
</>
})}
</Layout>
)
}
export default Home
The above given is my Home.js. I don't know why it is showing undefined. I tried to change the 'movies' in 'movies.map' to 'Movies' and so but it didn't do that much. This error is happening when iam trying to add a item to the watchlist table i created in supabase database. And i need to add the movie 'id' iam getting from the item to watchlist table. when i tried this
const {data, error} = await supabase.from("watchlists").insert({movie_id : movie?.id, user_id: auth.user.id})
like adding? in 'movie.id' it works but i don't get the id because of the? . So how can i add the movie id to the list by fixing this error. I really appreciate the help. thanks in advance.
The?. operator is like the. chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.
so in the below code user_id: auth?.user?.id it will not be accessible until it is nullish and if it's null it will return undefined instead of crashing an application.
const {data, error} = await supabase.from("watchlists").insert({movie_id : movie?.id, user_id: auth?.user?.id})
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.