Home > OS >  React sending async state from parent to child component after fetch in a functional component
React sending async state from parent to child component after fetch in a functional component

Time:03-11

I'm trying to send async state value from parent to child after setting state of a data coming from fetch API:

Profile.js

function Profile() {
  const { id } = useParams();
  const [user, setUser] = useState();

  useEffect(() => {
    const getUser = async () => {
      const response = await fetch(`http://localhost:8000/users/${id}`);
      const data = await response.json();
      setUser(data);
    };

    getUser();
  }, [id]);


   return (
    ...

    <Feed id={user._id} />

    ...
  )
}

Feed.js

function Feed(id) {

  const { user, isLoading, error } = useContext(AuthContext);

  useEffect(() => {
    const getPosts = async () => {
      const response = id
        ? await fetch(`http://localhost:8000/${id}`)
        : await fetch(`http://localhost:8000/home/${user._id}`);

      const data = await response.json();
      setPosts(data);
    };

    getPosts();
  }, [id, userId, user._id]);

  ...
}

on Profile.js component i solved the issue by using the optional chaining operator ?

  <div className={profileStyles.userItem}>
    phone: <span>{user?.phone}</span>
  </div>

but i dont know how to tell the Feed.js component to wait for id prop, so it will be null and the Feed.js component will not re-render, how to fix it?

CodePudding user response:

If you want to wait for the user to be fetched, you can render Feed only when the user is not undefined (so it waits that it is fetched):

{user && <Feed id={user._id} />

This way, the component Feed will be rendered only when the user is not undefined

  • Related