Skip to content Skip to sidebar Skip to footer

How Can I Receive Data That Was Sent By Express On Functional Component?

function Header(props) { const [ serverData, setServerData ] = useState({}); fetch('http://localhost:4001/api') .then(res => res.json()) .then((data) => {

Solution 1:

Use useEffect hook if you want to do this. If will happen once unless the dependencies change (no dependencies listed here).

function Header(props) {  
  const [ serverData, setServerData ] = useState({});

  useEffect(() => {
    fetch('http://localhost:4001/api')
      .then(res => res.json())
      .then((data) => {
        setServerData(data);
        console.log(data);
      });
  }, []);

  return (
      <div>{serverData}</div>
  );
}

Post a Comment for "How Can I Receive Data That Was Sent By Express On Functional Component?"