Next.js Discord

Discord Forum

Problem with CRUD Application

Unanswered
Villano de Las Encartaciones posted this in #help-forum
Open in Discord
Villano de Las EncartacionesOP
I have a nextjs app directory application running with laravel sanctum api,

i did this in my hooks/post.js
const getPost = async (postId) => {

        try {
            const response = await axios.get('api/posts/' + postId);
            return response.data.post;
        } catch (error) {
            if (error.response && error.response.status === 403) {
                throw new Error('Forbidden');
            } else {
                throw error;
            }
        }
    }

and then i did this in my EditForm
'use client'

import { usePosts } from "@/hooks/post"
import { useState } from "react"
import InputError from "@/components/InputError";
import styles from "../page.module.css";

const PostEditForm = ({params}) => {

    const { getPost } = usePosts();
    const { updatePost } = usePosts()

    const [post, setPost] = useState(null);
    const [title, setTitle] = useState('')
    const [body, setBody] = useState('')
    const [errors, setErrors] = useState([])

   const fetchPost = async () => {
        try{
            const postData = await getPost(params.id)

            setPost(postData)
            setTitle(postData.title)
            setBody(postData.body)
        }catch(error){

        }
   }


    fetchPost()

    const submitForm = async event => {
        event.preventDefault()

        await updatePost(params.id,{
            title,
            body,
            setErrors
        })
        
    }


but the problem is that it keeps sending request to my api.

would really appreciate a help

7 Replies

I would recommend you to either move the data fetching to server component(recommended) or in useEffect
Villano de Las EncartacionesOP
could you show an example of how to do this please.
Villano de Las EncartacionesOP
Cheers let me do this, i will give you update soon
Villano de Las EncartacionesOP
I did what is in the documentation above but that did not resolve it