Next.js Discord

Discord Forum

How to fetch correctly

Answered
Yellowstripe scad posted this in #help-forum
Open in Discord
Yellowstripe scadOP
app/vote/[id]/page.tsx
const [foundSwitch, setFoundSwitch] = useState(null);
    const [isLoading, setLoading] = useState(false)
    useEffect(()=> {
        const getData = async () => {
            setLoading(true)
            const requestOptions = {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json',
                },
                body: JSON.stringify({ id: params.id }),
            };
            const query = await fetch("/api/switch", requestOptions)
            const response = await query.json()
            setLoading(false)
            setFoundSwitch(response)
            console.log(response)
        }
        getData()
    }, [])
    return (
        <VoteClient foundSwitch={foundSwitch} />
    )


app/api/switch/route.tsx
export async function POST(req: Request) {
    try {
        const body = await req.json();
        const { id } = body;
        // check if switch_id exists
        const foundSwitch = await db.preVotingSwitches.findUnique({
            where: { id: id }
        });

        if (!foundSwitch) {
            return NextResponse.json({ switch: null, message: "Switch does not exist" }, { status: 404 });
        }

        return NextResponse.json({ switch: foundSwitch, message: "Switch found" }, { status: 200 });
    } catch (error) {
        console.error("Error:", error); // Log the error for debugging
        return NextResponse.json({ message: "Something went wrong!" }, { status: 500 });
    }
}


it's being buggy, I want to get the switch and then console.log the foundSwitch value in the first section of code
Answered by Ray
setFoundSwitch(response.switch)
View full answer

1 Reply