'Render page on react after loading json

I have load() function:

async function load() {
    let url = `www.com/file.json`
    let data = await (await fetch(url)).json()
    return data
}

I need to render my page after loading my json file from server:

export const Page = async () => {
    const data_ = await load()
    return (
          <div className="page">
                content
          </div>
    )
}

How can i do it?



Solution 1:[1]

You need to use useEffect and useState

Here's how you could achieve this:

import {useState, useEffect} from 'react';

export const Page = () => {
  const [data, setData] = useState();
  useEffect(() => {
    async function load() {
      let url = `www.com/file.json`;
      let data = await (await fetch(url)).json();
      setData(data);
    }

    load();
  }, []);

  return <div className="page">{JSON.stringify(data)}</div>;
}

Replace JSON.stringify with data.something to show a particular field in the data

A couple of tips:

  • React components cannot be async functions
  • useState carries variables you need to render the page
  • useEffect is a function that lets your component handle calling async code or any other kind of side effect

Solution 2:[2]

You can use the hook useEffect() & useState() to load your data :

function load() {
    let url = `www.com/file.json`
    let data = await (await fetch(url)).json()
    return data
}

export const Page = async () => {
  const [data, setData] = useState(null)

  useEffect(() => {
    load().then((_data) => {
       setData(_data)
    })

  }, [])

  if (!data) {
    return <div>loading data...</div>
  }

  return (
    <div className="page">
      data is ready to use !
    </div>
  )
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ahmed Ghoneim
Solution 2 rcarette