DEV Community

Sushil
Sushil

Posted on Edited on

useEffect is not working in production

The useEffect does not run at all in the production env. Its works fine in the dev env

*the code:
*

"use client"

import axios from 'axios';
import React, { useState, useEffect } from 'react';
import PostList from '@/components/ui/list/PostList';
import { Post, PostsResponse } from '@/utils/types';

const Categories = () => {
    const [selectedCategory, setSelectedCategory] = useState<string>('nextjs');
    const [posts, setPosts] = useState<Post[]>([]);
    console.log("first", selectedCategory)
    console.log("posts", posts)


    const fetchPosts = async () => {
        try {
            const response = await axios.get<PostsResponse>(
                selectedCategory
                    ? `http://localhost:3000/api/posts?cat=${selectedCategory}`
                    : 'http://localhost:3000/api/posts'
            );
            console.log("res", response)
            setPosts(response.data.posts);
        } catch (error) {
            console.error('Error fetching posts:', error);
        }
    };
    useEffect(() => {

        fetchPosts();
    }, [selectedCategory])


    const categories: string[] = [
        "nextjs",
        "react",
        "redux",
        "typescript",
        "javascript"
    ];

    const handleCategoryClick = (category: string) => {
        setSelectedCategory(category);
    };

    return (
        <div className='flex flex-col justify-center gap-10 mt-10 mx-auto '>
            <h2 className='text-3xl font-bold tracking-wider'>Categories</h2>
            <div className='flex flex-col md:flex-row gap-4 w-full'>
                {categories.map((text, index) => (
                    <button
                        key={index}
                        className={`flex overflow-hidden justify-center items-center gap-4 border-2 text-xl font-medium shadow-xl bg-card py-3 px-6 rounded-lg cursor-pointer hover:shadow-sm hover:scale-105 transition-shadow duration-300 capitalize
              ${selectedCategory === text ? 'text-purple-500 boder-2 border-purple-500' : ''}`}
                        onClick={() => handleCategoryClick(text)}
                    >
                        {text}
                    </button>
                ))}
            </div>
            <div className='grid grid-cols-12 gap-4'>
                {posts.map((post: Post) => (
                    <PostList key={post.id} post={post} />
                ))}
            </div>
        </div>
    );
};

export default Categories;
Enter fullscreen mode Exit fullscreen mode

Top comments (7)

Collapse
 
tracygjg profile image
Tracy Gilmore • • Edited

Hi Sushil, Could you provide the console output from both environments please. I suspect it might be working in develop because of the double-pass checking React does, but only in develop. It might be worth adding a console.log in the useEffect itself. I would suggest trying to empty the dependency array (arg 2 or the useEffect).

Collapse
 
sushilmagare10 profile image
Sushil • • Edited

In the dev i do get the data an and also the response data

category nextjs
page.tsx:12 posts Array(0)
installHook.js:1 category nextjs
installHook.js:1 posts Array(0)
page.tsx:22 res {data: {…}, status: 200, statusText: 'OK', headers: AxiosHeaders, config: {…}, …}
page.tsx:22 res {data: {…}, status: 200, statusText: 'OK', headers: AxiosHeaders, config: {…}, …}
page.tsx:11 category nextjs
page.tsx:12 posts (5) [{…}, {…}, {…}, {…}, {…}]
installHook.js:1 category nextjs
installHook.js:1 posts (5) [{…}, {…}, {…}, {…}, {…}]

but when using the in-production

category nextjs
page.tsx:12 posts []
page.tsx:11 category nextjs
page.tsx:12 posts []length: 0[[Prototype]]: Array(0)

Collapse
 
tracygjg profile image
Tracy Gilmore •

Can you please update the source code in your post.

Thread Thread
 
sushilmagare10 profile image
Sushil •
useEffect(() => {
    console.log('useEffect triggered');
    fetchPosts();
}, []);
Enter fullscreen mode Exit fullscreen mode

didn't get any log

Thread Thread
 
tracygjg profile image
Tracy Gilmore • • Edited

I am sorry to say your code looks right to me and I don't have a solution for you. It is odd that the useEffect is not being triggered. I would expect it to fire once in prod and twice in dev strict mode.
I hope someone else spots something and if you discover the fault, please post the cause so I and others might learn.
youtube.com/watch?v=j8s01ThR7bQ

Thread Thread
 
sushilmagare10 profile image
Sushil •

For some reason, it started working today. I didn't change a single code line or update the packages. I just got a CORS error, where I just added a middleware for it and now its working fine

Thread Thread
 
tracygjg profile image
Tracy Gilmore •

Hi Sushil,
I am not sure my advice was of any consequence but I am glad you now have a solution.
Best regards, Tracy