Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading