Export constant in react js whom data is comming from php file

84 Views Asked by At

I am using Php with react js ,there is constant declared in react js constant file that is used all over the application ,initially it was hardcoded in react js like Export const thumburl="www.example.com"; and its imported in almost every part of application now the requirement is to generate this URL dynamically from db.so i created a php file which will return this url i want to use it in react js constant file and export that ,tried several things but wasn't able to get results. it would be great help if any one can provide me the full working method to do this Note : react js is not my domain

async function githubUsers() {
    let response = await fetch('https://example.com/api.php')
    let users = await response.json()
    return users;
}

export const thumbUrl=githubUsers();

tried above code but it couldn't assign the value below is the sample php code

     <?php
if (isset($_SERVER['HTTP_ORIGIN'])) { 
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS"); 
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    }
    $data = 'www.example.com/gallery/thumbs/';
    header('Content-Type: application/json');
    echo json_encode($data);
1

There are 1 best solutions below

2
cyberwombat On

The issue here is that you are fetching the constant using an async method so thumbUrl essentially contains a promise. If you were in NodeJS you would simply add an await statement: const thumbUrl = await githubUsers(); but in React you will want to fetch this using useEffect and store it in the state with useState such as:

export function SomeConponent() {
  const [thumbUrl, setThumbUrl] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch('https://example.com/api.php');
      const data = await response.json();
      setData(data);
    };

    fetchData();
  }, []);

  return (
    <div>ThumbsURL: { thumbsUrl }</div>
  )
}

Here's a nice write up. To store data throughout app you would want to use something like useContext - here's a post on this.

That being said many frameworks such as Next.js have "prefetching" methods made to do initial fetches like this.