2

I am clicking on a single post on homepage that'll send me to the clicked post's page. At this component's rendering I am dispatching an action from useEffect that will get the post data from backend. But useEffect doesn't gets triggered even a single time but page render's twice. Please help

import {
  Container,
  Typography,
  LinearProgress,
  CircularProgress,
  Paper
} from '@material-ui/core';
import React, {
  useEffect
} from 'react';
import {
  getPost
} from "../../actions/posts";
import Navbar from '../Navbar/Navbar';
import {
  useDispatch,
  useSelector
} from 'react-redux';
import {
  useParams
} from 'react-router-dom';
import useStyles from "./styles";

const PostDetails = () => {
    const dispatch = useDispatch();
    const {
      id
    } = useParams();
    const classes = useStyles();
    const {
      post,
      isLoading
    } = useSelector((state) => (state.posts));

    console.log(post);
    useEffect(() => {
      console.log(post);
      dispatch(getPost(id));
    }, [id, dispatch]);

    return ( < div >
        <
        Navbar color = "#808080" / > {
          isLoading ? ( < div > < LinearProgress / > < /div>) : 
            ( < Container className = {
                classes.root
              } >
              <
              Typography variant = "h1" > {
                post.title
              } < /Typography> <
              /Container>)}</div > )
          }
          export default PostDetails

My action:

export const getPost = (id) => async(dispatch) => {
  try {
    dispatch({
      type: "START_LOADING"
    });
    const {
      data
    } = await api.fetchPost(id);
    dispatch({
      type: "FETCH_POST",
      payload: {
        post: data
      }
    });
    dispatch({
      type: "END_LOADING"
    });
  } catch (error) {
    console.log(error);
  }
};

reducer:

export default (state = {
  isLoading: true,
  posts: []
}, action) => {
  switch (action.type) {
    case "START_LOADING":
      return { ...state,
        isLoading: true
      };

    case "FETCH_POST":
      return { ...state,
        post: action.payload.post
      };

    case "FETCH_ALL":
      return { ...state,
        posts: action.payload.data,
        currentPage: action.payload.currentPage,
        numberOfPages: action.payload.numberOfPages
      };

    case "CREATE":
      return { ...state,
        posts: [...state.posts, action.payload]
      };

    case "END_LOADING":
      return { ...state,
        isLoading: false
      };

    default:
      return "";
  }
}

My backend is fine since when i run the api request on localhost to backend it sends me a JSON object with post's data.

2
  • What does "useEffect doesn't gets triggered even a single time" mean? Commented Sep 1, 2021 at 17:43
  • It don't gets triggered on the initial render but I am getting 2 console.log values both undefined and console.log inside useEffect not triggers. This means that component rendered twice but useEffect was not triggered. Commented Sep 1, 2021 at 18:01

2 Answers 2

4

UseEffect gets triggered only when the values given inside the square brackets change. So, if you want it to get triggered only when loading the page for the first time, leave it blank.

useEffect(() => {
      console.log(post);
      await dispatch(findPost(id));
    }, []);
Sign up to request clarification or add additional context in comments.

8 Comments

It didn't worked. I am getting error "TypeError: Cannot read property 'title' of undefined"
is useeffect working? try console.log inside useeffect
@NamanKedia Did you read the error? You load "post" from state, but your selector loads "posts" plural.
Did you add await since dispatch() is an async function?
Please someone help! I had earlier made a similae web app but there was not such problem and I have even compared the code. Please help
|
0
dispatch(findPost(id)); //No findPost in ../../actions/posts

There is no findPost action. Do you think you should change it to getPost

dispatch(getPost(id)); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.