mac-s-g / react-json-view

JSON viewer for react
https://mac-s-g.github.io/react-json-view/demo/dist/
MIT License
3.42k stars 530 forks source link

src property must be a valid json object while waiting for Promise to resolve #433

Open Claim0013 opened 1 year ago

Claim0013 commented 1 year ago

Hey guys!

I found this issue but it didn't help at all -> https://github.com/mac-s-g/react-json-view/issues/181

image

I am passing a fetched json to the src property and apparently the viewer isn't waiting for the promise to resolve and throws the exception instantly.

export const fetchJsonByURL = (url) => {
  return axios.get(url)
    .then((res) => res.data)
    .catch((error) => {
      toast.error(`${error.message} at getting ${url}`);
      return null;
   });
};

The promise resolves right after the error. If I directly pass a json object to src, it works. I use an async/await method and pass it down to the component as such: <ReactJson src={getSrc()} collapseStringsAfterLength={40} ... />

Any tips?

nathanwaters commented 1 year ago

This works for me. Just adapt to suit axios...

  const [loading, setLoading] = useState(true);
  const [JSON, setJSON] = useState([]);

  useEffect(() => {
      fetch(url).then(async (x) => {
        const data = await x.json()
        setJSON(data)
        setLoading(false);
      });
  }, []);

  return loading ? <div /> : <ReactJson src={JSON} />;