0

So I am trying to make a react component which calls an API and displays that data in a table. The problem is that when I call the api with fetch, it does not update the d state, but if I print the the data in the fetch call to console, it does indeed appear, it just isn't setting the d state to that data coming from the call. When print d to the console log it says null. I have fetched data from the same API in other parts of my code in the same way as below and works fine but I don't know why it isn't working in this case. I have tried many things like having the d state in the dependency array or just removing that array all together.

const UnusualTable = () => {
  const [d, setD] = useState(null);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    if(!d) {
      fetch(api_url)
      .then((response) => response.json())
      .then((data) => setD(data))
      .then(console.log(d));
    }
    setLoading(false);
  }, []);
  return (
    <Grommet full theme={grommet} themeMode="dark">
      { loading != true ? (
       <Box> 
          <Table align="center" margin="small">
.
.
.
   );
}
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
upkash
  • 1
  • 1
  • `d` is in a stale closure. When you call `setD(data)`, it will re-render `UnusualTable` by calling the function and creating a new closure where `d` has a different value. The new value of `d` is not accessible from the closure which initiated the `fetch()`. – Patrick Roberts Apr 18 '21 at 22:10
  • thanks for replying, i am trying map d to a table in the return statement, but it says its still null, wouldnt that be a seperate closure? but in that question you suggested it says to add the state as a dependency which i have tried but doesnt fix the issue. – upkash Apr 18 '21 at 22:58
  • Your `return` statement has to handle both closures, not just the second one. Assume that `d` can be either `null` or `data` when the `return` statement is reached. – Patrick Roberts Apr 18 '21 at 23:46

0 Answers0