Home > front end >  React : i can't access to my state from my useEffect
React : i can't access to my state from my useEffect

Time:10-14

in the return of my react function I want to do a response.data.map(...), but I can't, "response" is undefined because it's in my useEffect (scope problem).

So I try to create a state with useState which will contain response.data, but the problem is that my console.log always returns undefined, the default state of my state.

So I try to use prevstate because I believe the problem is that the previous state is taken into account, but apparently the syntax is not good. :

const Comments = ({ postId }) => {

  // States 
  const [allComments, setAllComments] = useState()
  
  useEffect(() => {
    async function fetchData() {
      const data = {
        postId: postId,
      };
      const response = await POST(ENDPOINTS.GET_ALL_COMMENTS, data);
      if (response.data[0]) {
        setAllComments((prevState) => ({
          ...prevState,
          response.data
                    
        }))
      } else {
        
      }
    }
    fetchData();
    console.log(allComments)
  }, []);
  
  return (
           
      <div>
       {allComments.map(...)}
      </div>
      
    
  );
};

I finally try to do like this:

setAllComments ((prevState) => ({
          ... prevState,
          response
          
        }))

This time the syntax is good, but my console.log from allComments is still undefined ...

How do I access my response.data from my return? Should we use useState, prevstate, other?

CodePudding user response:

You can't .map() over an object ({}).

If your comments will be an array, you'll need to use the array spread operator ([..., ...]):

const Comments = ({ postId }) => {
  const [allComments, setAllComments] = useState([]);

  useEffect(() => {
    async function fetchData() {
      const response = await POST(ENDPOINTS.GET_ALL_COMMENTS, {
        postId,
      });
      const data = response.data;
      if (Array.isArray(data)) {
        setAllComments((prevState) => [...prevState, ...data]);
      } else {
        throw new Error("Oops, didn't get an array.");
      }
    }
    fetchData();
  }, [postId]);

  return <div>{JSON.stringify(allComments)}</div>;
};
  • Related