Home > Software engineering >  Render page on react after loading json
Render page on react after loading json

Time:02-04

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?

CodePudding user response:

You can use the useEffect hook to make the call when the component mounts, it will be called once and fetch the data you need, then it will set it in the data state to be used in the return inside the divs.

As you did not provide the structure of the response I cannot give a more detailed explanation on how to render the data itself. Also id_ has no use in your example but I kept it there to closely resemble your example.

import React, {useState, useEffect} from "react";

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

  useEffect(() => {
    const load = async (id_) => {
        let url = `www.com/file.json`
        let data = await (await fetch(url)).json()
        const manipulatedData = ...
        // do manipulation
        setData(manipulatedData)
    }
    load()
  }, [])

  return (
    <div className="page">
      {data ? data : null}
    </div>
  );
}

export default Page;

CodePudding user response:

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

CodePudding user response:

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>
  )
}
  •  Tags:  
  • Related